关于dplyr:在R:The Tidyverse-way中将列表列表转换为数据框

Converting a list of lists to a dataframe in R: The Tidyverse-way

我正在搜索将列表列表转换为R中的数据框的Tidyverse方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 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)

创建列表列表的数据框的非tidyverse方法:

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

问题

如何使用tidyverse(带有和不带有管道)将列表列表转换为数据框?


我喜欢这个版本,因为它保持了可读性,这对我来说是关于tidyverse

的最强要点

1
2
3
list_of_lists %>%
    map(as_tibble) %>%
    reduce(bind_rows)

您可以使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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


您可以尝试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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