Xander Xander - 29 days ago 7
R Question

Merging df.1, df.2, df.3 ... df.x into one dataframe

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!

Answer

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.frames.

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

Comments