unnest a list in r

To unnest a list in R, you can use the unnest() function from the tidyr package or you can use the purrr package with the map() function.

Here is an example of how to use unnest() function:

main.r
library(tidyr)

# create a list
my_list <- list(a = 1:3, b = c("x", "y", "z"))

# unnest the list
my_df <- unnest(my_list)

# view the resulting data frame
my_df
162 chars
11 lines

Output:

main.r
# A tibble: 6 x 2
      a b    
  <int> <chr>
1     1 x    
2     2 y    
3     3 z    
4     1 x    
5     2 y    
6     3 z    
130 chars
10 lines

Alternatively, you can use purrr with the map() function to achieve the same result:

main.r
library(purrr)

# create a list
my_list <- list(a = 1:3, b = c("x", "y", "z"))

# unnest the list
my_df <- map_df(my_list, ~data.frame(value = .x))

# view the resulting data frame
my_df
187 chars
11 lines

Output:

main.r
  value
1     1
2     2
3     3
4     x
5     y
6     z
56 chars
8 lines

gistlibby LogSnag