transform a list into a dataframe in long form in r

You can transform a list into a dataframe in long form in R using the enframe() function from the tibble package in combination with unnest() from the tidyr package, or by using the stack() function. Here's an example of how to do it:

main.r
# create a sample list
my_list <- list(a = c(1, 2, 3), b = c(4, 5, 6), c = c(7, 8, 9))

# method 1: using enframe() and unnest()
library(tibble)
library(tidyr)
library(purrr)

my_list %>% 
  enframe() %>% 
  unnest(value) %>%
  rename(key = name, value = value)

# method 2: using stack()
my_df <- stack(my_list)
my_df

# method 3: using data.frame() and names()
my_df <- data.frame(
  key = rep(names(my_list), sapply(my_list, length)),
  value = unlist(my_list)
)
my_df
472 chars
24 lines

In all the above examples, my_list is the input list and my_df is the output dataframe in long form. The key column represents the names of the elements in the list, and the value column represents the values of the elements.

Note that the enframe() function returns a dataframe with a column named name and a column named value, so we need to rename name to key to match the desired output. The stack() function also returns a dataframe with columns named values and ind, so we can simply assign the result to my_df. The data.frame() method requires us to create the key column manually using rep() and the value column using unlist().

gistlibby LogSnag