2

Possible Duplicate:
writing many files in a for loop using R

I am trying to figure our how I can write data to many different files using a for loop:

for example:

for (i in 1:4)
{

x = i
write(x, file = "C:\\Documents and Settings\\user\\Desktop\\R_stuff\\testi.txt", append = FALSE, sep = ",")

}

I want to create 4 text files: test1 that contains 1; test2 that contains 2; test3 that contains 3; test 4 that contains 4.

However, I don't know the syntax that will allow the loop the change the name of the text file on each iteration. Obviously my "testi.txt" doesn't work :).

Thank You in advance.

Community
  • 1
  • 1
Akavall
  • 82,592
  • 51
  • 207
  • 251

1 Answers1

4

To save to multiple files you need to construct a custom filename inside the loop. An option is paste:

paste("basename", i, ".bla", sep = "")

alternatively:

sprintf("basename%s.bla", i)
Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
  • or maybe better (if you have more than 9 files): `sprintf("file%03d.bla", i)`; that will make like file001, file002, etc. – Tomas Dec 02 '11 at 21:38