3

I am searching for the Tidyverse way of converting a list of lists to a dataframe in R.

# Create a list of lists:
a <- seq(1,10,1)
b <- seq(1,20,2)

# Function to calculate the sum 
# (just an example, I am aware of the base R sum())

sum_test <- function(a=a, b=b){
  sum <- a+b
  df <- cbind(a,b,sum)
  return(df)
}

list_of_lists <- purrr::map2(a,b,sum_test)

Non-tidyverse way to create a dataframe of the list of lists:

df <- as.data.frame(do.call(rbind, list_of_lists))

Question

How to convert a list of lists to a dataframe using tidyverse (with and without a pipe)?

user213544
  • 2,046
  • 3
  • 22
  • 52

3 Answers3

2

You could use

purrr::map_df(list_of_lists, tibble::as_tibble)

# A tibble: 10 x 3
#      a     b   sum
#   <dbl> <dbl> <dbl>
# 1     1     1     2
# 2     2     3     5
# 3     3     5     8
# 4     4     7    11
# 5     5     9    14
# 6     6    11    17
# 7     7    13    20
# 8     8    15    23
# 9     9    17    26
#10    10    19    29
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
2

I like this version, as it keeps the readability which is for me the strongest point about the tidyverse

list_of_lists %>%
    map(as_tibble) %>%
    reduce(bind_rows)
Georgery
  • 7,643
  • 1
  • 19
  • 52
1

You can try:

map2_df(.x = a, 
        .y = b, 
        ~ sum_test(.x, .y) %>%
         as.data.frame())

    a  b sum
1   1  1   2
2   2  3   5
3   3  5   8
4   4  7  11
5   5  9  14
6   6 11  17
7   7 13  20
8   8 15  23
9   9 17  26
10 10 19  29
tmfmnk
  • 38,881
  • 4
  • 47
  • 67