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

会有一股神秘感。 提交于 2019-11-28 01:46:14

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, ...).

Those all seem complicated ;). The answers above seem to be operating on "we have a list of objects with very similar names, how do we handle that". Answer: they don't need to have very similar names. They don't even have to be different objects.

If you read the files in not through a for loop, but through lapply(), you get a single object that contains all of the data frames - each one as a single element. These can then trivially be extracted. So you'd have something that looks like...

#Grab a list of filenames
filenames <- list.files("save", pattern="*.csv", full.names=TRUE)

#Iterate through that list of names, using lapply(), reading the data in.
list_of_data_frames <- lapply(filenames, function(x){

    #Read the data in
    to_return <- read.csv(x)[!is.na(30),][c(9:104,657:752),c(15,27,28,29,30,33,35)])

    #Return it. You could save lines of code (and processor time!) by just reading
    #straight into return(), but it would be a lot less clear.
    return(to_return)
})

#Now use do.call to turn it into a single data frame.
data.df <- do.call("rbind", list_of_data_frames)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!