I want to save a lot of dataframes via a for loop or a function

44 Views Asked by At

I have different data frame sorted by year in a list

mydata<-list()
mydata[["2010"]]<-data.frame(Age=c(12,13),Year=rep("2010",2))
mydata[["2011"]]<-data.frame(Age=c(14,15),Year=rep("2011",2))
mydata[["2012"]]<-data.frame(Age=c(16,17),Year=rep("2012",2))
mydata[["2013"]]<-data.frame(Age=c(18,17),Year=rep("2013",2))
mydata[["2014"]]<-data.frame(Age=c(16,27),Year=rep("2014",2))

Instead of saving the list as an RData file, I want to save each object in the list separately.

But first, I want each dataset to be placed in an object indicating the year.

For example for the Year 2010 like this:

mydata_2010<-mydata[["2010"]]
save(mydata_2010,file = "mydata_2010.RData")

With a for loop or a function, I want to do all this at one go

I succeeded to assign datasets for a particular year to an object indicating the same year

for (i in as.character(2010:2012)) {
  assign(paste0(
    "mydata_",i,sep=""
  ),mydata[[i]])
  
}

But I dont know to save theses objects via the function save

I tried this and it does not works

for (i in as.character(2010:2012)) {
      save(assign(paste0(
        "mydata_",i,sep=""
      ),mydata[[i]]), file=paste0("mydata_",i,".RData",sep="")
      
    }
0

There are 0 best solutions below