From Tidy Data To A Named List in R
Cruel world sometimes forces you to use lists instead of simple tables. Here’s a small snippet for grabbing names and values from a dataframe and combining them into a named list. Each name in the list has one or more values.
library(tidyverse)
pivot_to_list <- function(data, names_from, values_from) {
nested_data <- data %>%
select(names = {{ names_from }}, values = {{ values_from }}) %>%
tidyr::nest(values = values)
list_names <- nested_data %>%
pull("names")
list_values <- nested_data %>%
pull("values") %>%
purrr::map(pull, "values")
named_list <- magrittr::set_names(list_values, list_names)
return(named_list)
}