Combine multiple .RData files containing objects with the same name into one single .RData file

筅森魡賤 提交于 2019-11-30 15:29:56

I think the best answer I saw was the code below, which I copied from an SO answer which I can't track down right now. Apologies to the original author.

resave <- function(..., list = character(), file) {
   previous  <- load(file)
   var.names <- c(list, as.character(substitute(list(...)))[-1L])
   for (var in var.names) assign(var, get(var, envir = parent.frame()))
   save(list = unique(c(previous, var.names)), file = file)
}
#I took advantage of the fact the load function 
#returns the name of the loaded variables, so 
#I could use the function's environment instead of creating one.
#And when using get, I was careful to only look in the 
#environment from which the function is called, i.e. parent.frame()
JWilliman

Here's an option that incorporates several existing posts

all.files = c("file1.RData", "file2.RData", "file3.RData")

Read multiple dataframes into a single named list (How can I load an object into a variable name that I specify from an R data file?)

mylist<- lapply(all.files, function(x) {
  load(file = x)
  get(ls()[ls()!= "filename"])
})

names(mylist) <- all.files #Note, the names here don't have to match the filenames

You can save the list, or transfer the dataframes into the global environment prior to saving (Unlist a list of dataframes)

list2env(mylist ,.GlobalEnv)

Alternatively, if the dataframes were identical and you wanted to create a single big dataframe, you could collapse the list and add a variable with names of contributing files (Dataframes in a list; adding a new variable with name of dataframe).

all <- do.call("rbind", mylist)
all$id <- rep(all.files, sapply(mylist, nrow))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!