逐行合并全局环境中的多个数据帧(rbind) [英] Combine several data frames in the global environment by row (rbind)

查看:76
本文介绍了逐行合并全局环境中的多个数据帧(rbind)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个项目中,该项目将从给定文件夹中导入所有csv文件并将它们合并到一个文件中。我能够从文件夹中的每个文件导入想要的行和列,但是现在需要帮助将它们全部合并到一个文件中。我不知道最终会得到多少文件(大约120个文件),所以我不想将它们一一合并。

I am working on a project that imports all csv files from a given folder and merges them into one file. I was able to import the rows and columns I wanted from each of the files from the folder but now need help merging them all into one file. I do not know how many files I will eventually end up with (probably around 120) so I do not want to merge them 1 by 1.

这是我所拥有的到目前为止:

Here is what I have so far:

 # Import All files
 rowsToUse <- c(9:104,657:752)
 colsToUse <- c(15,27,28,29,30,33,35)
 filenames <- list.files("save", pattern="*.csv", full.names=TRUE)
 for (i in seq_along(filenames)) {
   assign(paste("df", i, sep = "."), read.csv(filenames[i])[!is.na(30),][rowsToUse,colsToUse])
 }

 # Merge into one file
 for (i in seq_along(filenames)) {
   df<-rbind(df.[i])
 }

代码的第一部分创建一个系列数据帧标记为df.1,df.2等。我希望它们最终出现在一个称为df的最终数据帧中。所有文件的结构都相同。

The first part of the code creates a series of dataframes labled df.1, df.2, etc. I would like them to end up in one final dataframe called df. All files are identical in structure.

如果有人多花一点时间,我将非常感谢您的帮助!谢谢!

I would really appreciate some help if someone has a few extra minutes! Thank you!

推荐答案

由于已经读取了文件,因此可以尝试以下操作:

Since you have already read the files in, you can try the following:

do.call(rbind, mget(ls(pattern = "df")))

ls(pattern = df)应该捕获您的所有 df.1, df.2 , 等等。希望您没有使用相同的模式命名其他东西,但是如果您这样做,请尝试使用更严格的模式,直到命令仅列出您的 data.frame s。

The ls(pattern = df) should capture all of your "df.1", "df.2", and so on. Hopefully you don't have other things named with the same pattern, but if you do, experiment with a stricter pattern until the command lists just your data.frames.

mget()会将所有这些内容放入列表您可以在其上使用 do.call(rbind,...)

mget() will bring all of these into a list on which you can use do.call(rbind, ...).

这篇关于逐行合并全局环境中的多个数据帧(rbind)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆