将df.1,df.2,df.3 ... df.x合并到一个数据帧中 [英] Merging df.1, df.2, df.3 ... df.x into one dataframe
问题描述
我正在处理从一个给定文件夹导入所有csv文件并将它们合并到一个文件中的项目。我可以从文件夹中的每个文件导入我想要的行和列,但现在需要帮助将它们全部合并到一个文件中。我不知道最终会有多少文件(大概在120左右),所以我不想把它们合并1。
这是我有的到目前为止:
#导入所有文件
rowsToUse < - c(9:104,657:752)
colsToUse< - c(15,27,28,29,30,33,35)
文件名< - 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])
}
#合并到一个文件
for(i in seq_along(filenames)){
df < rbind(df。[i])
}
代码的第一部分创建一个一系列数据框架标注df.1,df.2等。我希望他们最终在一个名为df的最终数据框中。所有文件的结构相同。
如果有人需要额外的几分钟,我真的很感激一些帮助!谢谢!
由于您已经阅读过这些文件,您可以尝试以下操作:
do.call(rbind,mget(ls(pattern =df)))
ls(pattern = df)
应该捕获你所有的df.1,df.2 , 等等。希望你没有其他以相同模式命名的东西,但是如果你这样做,则尝试使用更严格的模式,直到命令列出你的 data.frame
s。 p>
mget()
将所有这些都纳入列表
您可以使用 do.call(rbind,...)
。
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])
}
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")))
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.frame
s.
mget()
will bring all of these into a list
on which you can use do.call(rbind, ...)
.
这篇关于将df.1,df.2,df.3 ... df.x合并到一个数据帧中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!