Search code examples
rloopscsvdataframedatalist

How to Write Multiple CSV from List of Dataframe at once in R?


I have thousands .csv files which consists this information:

Year  HS
1956  1.098
1956  1.785
1956  0.987
....
2012  1.341

What I should be doing are:

  1. Found Maximum HS for each Year on each file
  2. Write thousands separate .csv files which hold information of point 1

As far (also by help in this forum), I've a list of thousands dataframes of point 1 with this script:

    temp <- Sys.glob("*.csv")
ag <- lapply(temp, function(f) 
  aggregate(HS ~ Year, read.table(f, header = TRUE, sep = ";"), max))

The list look like this:

[[1]]
   Year    HS
1  1956 2.172
2  1957 1.831
3  1958 1.713
.....
56  2011 2.332
57  2012 2.917

[[2]]
   Year    HS
1  1956 2.111
2  1957 1.864
3  1958 1.135
.....
56  2011 1.032
57  2012 2.341
.....
until thousands dataframes

I am trying to write .csv files from those list by applying these script:

    temp <- Sys.glob("*.csv")
ag <- lapply(temp, function(f) 
  aggregate(HS ~ Year, read.table(f, header = TRUE, sep = ";"), max))
for(i in 1:length(ag)){
  write.csv(ag[i],file="out[i].csv")
}

But it only create out[i].csv which consists information of first dataframe of ag

I am also trying this script:

temp <- Sys.glob("*.csv")
ag <- lapply(temp, function(f) 
  aggregate(HS ~ Year, read.table(f, header = TRUE, sep = ";"), max))
lapply(ag, function(a) 
  write.csv(a, file="out[a].csv"))

And again, it only create out[a].csv which consists information of first dataframe of ag.

It seems that I fail to set the loop both to 'call' the dataframes on the list and to create sequential output .csv name. Is there any suggestion for this issue?

Thank you.


Solution

  • Try

    write.csv(ag[i],file=sprintf("out%d.csv",i))
    

    or

    write.csv(ag[i],file=paste0("out",i,".csv"))
    

    I wasn't sure whether you wanted to square brackets in the file name. I would advise against it.