r - 将多个数据帧列表绑定到一个列表中
问题描述
我正在寻找一种更优雅或更有效的解决方案,将多个数据帧列表附加到一个列表中。为简单起见,假设我们处理以下情况:
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]]))
我希望最终输出为包含附加数据帧的列表。
谢谢你。
解决方案
一种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
#...
#...
推荐阅读
- asp.net-core - ASP.NET Core MVC:模型绑定和复杂类型
- php - 如何获取表单选择值以显示正在插入的表中的两件事?
- javascript - Webpack + Typscript 库导入在 React 项目中未定义
- google-app-engine - 用于从应用程序引擎 flex 检查任务队列长度的 API?
- javascript - JavaScript InnerHTML 未更新
- node.js - 为什么我的 websocket 握手失败并出现意外响应 200?
- apache-spark - Spark jdbc覆盖模式未按预期工作
- c# - 如何使表单在打开表单时加载图片框中的随机图像,使按钮在图片框中显示不同的图像
- jsf - 带有 StickyHeader 的数据表在 Primefaces 8.0 的选项卡视图中显示重复的标题
- sql - 如何在 SQL Server 中将一列数字变成一个单元格?(找出所有小于 1000 的素数)