【问题标题】:rbind multiple lists of dataframes into a list将多个数据帧列表绑定到一个列表中
【发布时间】:2021-08-10 13:49:33
【问题描述】:

我正在寻找一种更优雅或更高效的解决方案,将多个数据框列表附加到一个列表中。为简单起见,假设我们处理以下情况:

my_func <- function(i) {
  # function to generate a list with two data frames
  head(cars, i * 5) -> df1
  head(iris, i * 5) -> df2
  
  return(list(df1, df2))      
}

假设我们要执行函数my_func 3 次,并在列表中执行rbind 的结果:

#output

Map(rbind, my_func(1), my_func(2), my_func(3)) -> out
#this would not be so elegant if we have to run the function many times. 

#or 

for (i in 1:3) {      
  if (i == 1) {        
    out <- my_func(i)        
  } else {        
    out <- Map(rbind, out, my_func(i))
  }      
}

我不是在寻找这样的东西:

do.call(rbind, lapply(1:3, function(i) my_func(i)[[1]])) 
do.call(rbind, lapply(1:3, function(i) my_func(i)[[2]]))

我希望最终输出为包含附加数据帧的列表。

谢谢。

【问题讨论】:

  • 这些数据框的维度都一样吗?
  • @AnoushiravanR 是的,它们的列数和名称完全相同。行数可能不同,但这应该不是问题。

标签: r apply purrr


【解决方案1】:

tidyverse 的一种方式是 -

library(dplyr)
library(purrr)

map(1:3, my_func) %>% transpose() %>% map(bind_rows)

#[[1]]
#   speed dist
#1      4    2
#2      4   10
#3      7    4
#4      7   22
#5      8   16
#6      4    2
#7      4   10
#8      7    4
#...
#...

#[[2]]
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#1           5.1         3.5          1.4         0.2  setosa
#2           4.9         3.0          1.4         0.2  setosa
#3           4.7         3.2          1.3         0.2  setosa
#4           4.6         3.1          1.5         0.2  setosa
#5           5.0         3.6          1.4         0.2  setosa
#6           5.1         3.5          1.4         0.2  setosa
#...
#...

【讨论】:

  • 使用transpose 的好方法。谢谢!
【解决方案2】:

我们可以使用

map(1:3, my_func) %>% 
     transpose %>% 
     lapply(bind_rows)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-18
    • 2021-07-25
    • 2023-03-27
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多