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

后端 未结 2 1714
Happy的楠姐
Happy的楠姐 2020-12-16 05:57

I have many many .RData files containing one dataframe that I had saved in a previous analysis and the data frame has the same name for each file loaded. So for example usin

2条回答
  •  感动是毒
    2020-12-16 06:14

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

提交回复
热议问题