我试图写一段代码来组合多个数据帧(大约100个),其中每个数据帧都以变量名output1,output2,...,output100存储。我想使用rbind函数将这些数据帧合并到一个数据帧中,但它不起作用,因为我必须重新编写每个变量的名称。
我需要一个建议,写所有的变量名在一次go或在一个循环的形式。
问题:我试着把代码写成rbind(output1,output2,output3,...,output100),这是非常冗长乏味的。
发布于 2020-05-19 16:15:47
您可以使用mget
。示例:
调用ls()
将为您提供工作区中的对象名称。
ls()
# [1] "n" "out.lst" "output.1" "output.2" "output.3" "something.else"
然后使用mget
通过pattern=
抓取数据帧,并使用do.call
对其进行rbind
。
output.long <- do.call(rbind, mget(ls(pattern="output.")))
# x y z
# output.1.1 1 1 2
# output.1.2 5 5 4
# output.2.1 2 1 4
# output.2.2 5 4 1
# output.3.1 5 4 2
# output.3.2 2 2 3
玩具数据:
set.seed(42)
n <- 3
out.lst <- setNames(replicate(n, data.frame(x=sample(1:5, 2),
y=sample(1:5, 2),
z=sample(1:5, 2)), simplify=F),
paste0("output.", 1:n))
list2env(out.lst, env=.GlobalEnv)
发布于 2020-05-19 17:31:22
如果您愿意使用tidyverse包,您可以将output
创建为一个列表,然后只需编写,比如说combined <- bind_rows(output)
。这与首先使用lapply()
创建数据帧很自然地契合。
未测试的代码
library(tidyverse)
output <- lapply(1:length(inputFiles), function(x) read.csv(inputFiles[x]))
combined <- bind_rows(output)
https://stackoverflow.com/questions/61890179
复制