rfor-loopdta

Using for loop to write data frame as dta file in R


I have data frames in a list a and I want to use a loop to save these as both rda and write as dta. I don't get why I get the error message that object data frame cannot be found:

for (f in a) {
  for (name in 1:length(filenames)) {
    save(as.data.frame(f),file = paste("~/Dropbox/Data_Insert/Panels/",name,end_rda,sep=""))
    write.dta(as.data.frame(f),file = paste("~/Dropbox/Data_Insert/Panels/",name,end_dta,sep=""))
         }
}

Error in save(as.data.frame(f), file = paste("~/Dropbox/Data_Insert/Panels/",  : 
  object ‘as.data.frame(f)’ not found

So by f, this would be indexing the data frame in the list? I did as.data.frame(f) because when I only used f, I got the message:

The object "dataframe" must have class data.frame

I changed the code to for f in a, but it still returns an error saying that as.data.frame(f) not found.


Solution

  • I think that this is what you are trying to do. I assume that a is a list of data frames and filenames is a character vector of the same length.

    for (i in 1:length(a)) {
      to_save = as.data.frame(a[[i]])
      save(to_save, file = paste0("~/Dropbox/Data_Insert/Panels/", filenames[i], end_rda))
      write.dta(to_save, file = paste0("~/Dropbox/Data_Insert/Panels/", filenames[i], end_dta))
    }
    

    Note that save preserves the name of the R object, so when you load any of these files it will be loaded into the workspace with the name to_save. This seems bad. For individual R objects I would strongly encourage you to use saveRDS and create .RDS files instead of save. See, e.g., Ricardo's answer to this question for an example of Rda vs RDS.