Brian P
Brian P

Reputation: 1516

Using index or counter to write data frames

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!

Upvotes: 0

Views: 78

Answers (1)

cmaimone
cmaimone

Reputation: 171

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="")) 
}

Upvotes: 3

Related Questions