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!

1 Answer 1

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="")) 
}
Sign up to request clarification or add additional context in comments.

1 Comment

paste0("a", i, ".csv") is a convenient alternative for the common case when sep=""; I prefer sprintf("a%d.csv", i).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.