2

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

# 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 方法:

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

问题

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

4

3 回答 3

2

你可以使用

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
于 2020-01-27T10:05:16.810 回答
2

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

list_of_lists %>%
    map(as_tibble) %>%
    reduce(bind_rows)
于 2020-01-27T10:13:22.240 回答
1

你可以试试:

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
于 2020-01-27T10:01:58.347 回答