Search code examples
rloopsdataframesaving-data

Looping through dataframe names in R and saving out corresponding dataframe as Rds file


I have about 30 separate dataframes loaded in my R session each with various names. I also have a character vector called mydfs which contains the names of all those dataframes loaded into my R session. I am trying to loop over mydfs and save out as an rds file each dataframe listed in the elements of mydfs, but for some reason, I'm only able to save out the character string of the name of the dataframe I'm trying to save (not the datafame itself). Here is simulated, reproducible example of what I have:

#Create vector of dataframes that exist in base r to create a reproducible example
mydfs<-c("cars","iris","iris3","mtcars")

#My code that creates files, but they don't contain my dataframe data for some reason
for (i in 1:length(mydfs)){
  savefile<-paste0(paste0("D:/Data/", mydfs[i]), ".Rds")
  saveRDS(mydfs[i], file=savefile)
  print(paste("Dataframe Saved:", mydfs[i]))
}

This results in the following log output:

[1] "Dataframe Saved: cars"
[1] "Dataframe Saved: iris"
[1] "Dataframe Saved: iris3"
[1] "Dataframe Saved: mtcars"

Then I try to read back in any of the files I created:

#But when read back in only contain a single character string of the dataframe name
a<-readRDS("D:/Data/iris3.Rds")
str(a)


chr "iris3"

Note that when I read iris3.Rds back into a new R session using readRDS, I don't have a dataframe as I was expecting, but a single character vector containing the name of the datafame and not the data.

I haven't been programming in R for a while, since my current client preferred SAS, so I think I am somehow getting macro variable looping in SAS confused with R and so that when I call saveRDS, I'm passing in a single character vector instead of the actual dataframe. How can I get the dataframe to be passed into saveRDS instead of the character?

Thanks for helping me untangle my SAS thinking with my somewhat rusty R thinking.


Solution

  • You're currently just saving the names of the dataframes. You can use the get function as follows:

    mydfs<-c("cars","iris","iris3","mtcars")
    
    for (i in 1:length(mydfs)){
      savefile<-paste0(paste0("D:/Data/", mydfs[i]), ".Rds")
      saveRDS(get(mydfs[i]), file=savefile)
      print(paste("Dataframe Saved:", mydfs[i]))
    }
    
    readRDS('D:/Data/iris3.RDS')