0

I'm sure this has been asked before, but no luck finding the answer. If I want to write 10 separate files as part of a loop, how do I go about using the index or counter to increment the name of the files.

a <- matrix(5, nrow=5, ncol=5)

for(i in 1:10){
    a <- a + 1
    write.csv(a, "a1.csv") 
}

Thus, I would like to extend this code to write 10 files: a1.csv, a2.csv, a3.csv, and so on. I'm assuming the answer is straightforward, perhaps using paste0, assign, and [i]. No luck getting it solved! Of course, if there is a better way to approach this problem without a for loop, I'm open to suggestions!

Brian P
  • 1,496
  • 4
  • 25
  • 38

1 Answers1

3

As in this answer, just use paste:

a <- matrix(5, nrow=5, ncol=5)

for (i in 1:10) {
  a <- a + 1
  write.csv(a, paste("a",i,".csv",sep="")) 
}
Community
  • 1
  • 1
cmaimone
  • 171
  • 1
  • 5
  • 2
    `paste0("a", i, ".csv")` is a convenient alternative for the common case when `sep=""`; I prefer `sprintf("a%d.csv", i)`. – Martin Morgan Dec 03 '14 at 00:54