Search code examples
rloopsfor-loopsaveload

Saving data frames as .Rda files and loading them using loops


I have three data frames: sets, themes, and parts. I want to save each as a .Rda file, and then (to prove that they saved correctly) clear my workspace and load each of them.

Without a loop, this obviously works:

save(sets, file = "sets.Rda")
save(themes, file = "themes.Rda")
save(parts, file = "parts.Rda")

rm(list=ls())
load("sets.Rda")
load("themes.Rda")
load("parts.Rda")

Looping through this SEEMS like it should be straightforward, but I can't get it to work. I have a few ideas about what's the issue, but I can't work my way around them.

My thought is this:

DFs <- list("sets", "themes", "parts")
for(x in 1:length(DFs)){
  dx <- paste(DFs[[x]], ".Rda", sep = "")
  save(x, file = dx)
}

rm(list=ls())
DFs <- list("sets.Rda", "themes.Rda", "parts.Rda")
for(DF in DFs) {
  load(DF)
}

I know that loading loop can work because when I save the files using the first (non-looping) bit of code, it loads them all properly. But something about saving them using the above loop makes it so that when I run the loading loop, I don't get what I want. Get one object, named "x" with a value of "3L". I don't get it.

Please help me out. I think the problem rests in the arguments of my save() function, but I am not sure what's up.


Solution

  • Here's a minimal reproducible example showing how to write data.frames as RDS files in a loop, and then read them back into the R environment in a loop:

    # Make 3 dataframes as an example
    iris1 <- iris2 <- iris3 <- iris
    
    df_names <- c("iris1", "iris2", "iris3")
    
    # Saving them
    for (i in 1:length(df_names)) {
      saveRDS(get(df_names[i]), paste0(df_names[i], ".RDS"))
    }
    
    # Confirm they were written
    dir()
    # [1] "iris1.RDS" "iris2.RDS" "iris3.RDS"
    
    # Remove them 
    rm(iris1, iris2, iris3)
    
    # Load them
    for (i in 1:length(df_names)) {
      assign(df_names[i], readRDS(paste0(df_names[i], ".RDS")))
    }