How to use for loop to save and write files in R

Viewed 1814

I have multiple data frame objects, for instance df1, df2 and so on. I want to use a for loop to save and write these files to dta, but I can't figure out where to start. Should I save the data frame objects to a list, and then save them? For instance:

a = list()
# write for loop saving each data frame objects to a list then

f = c("df1","df2" .. )

end = ".RDA"

for (i in length(a)) {
  for (f in filenames) {
    save(a[[i]],file = paste("~/Panel",filename,end,sep="")
  }
}
2 Answers

If you want to save multiple data frames to ONE rda file, you don't need for loops:

a <- list(d1, d2)    
save(a, file = paste("~/Panel/",filename,end,sep=""))

If you want to save the data frames one by one to .rda files and use a for loop, you can create a named list and then use these names in the loop to name the files:

df1 <- data.frame(a = rnorm(5), b = rnorm(5))
df2 <- data.frame(c = rnorm(5), d = rnorm(5))

files <- list(df1=df1, df2=df2)

for(f in 1:length(files)) {
    save(f, file = paste0(names(files[f]), ".rda"))
}
Related