[R] Referring on the value of a counter in a loop

Chris Kopp kopp at soz.unibe.ch
Mon Jul 24 11:31:02 CEST 2006


Dear all

The following is a very basic and beginner's question on loops.

Suppose you have data (say, 1000 cases) with two variables named  
"answer" (string) and "class" (numeric). The latter runs from 1 to 78  
and categorizes the data. I need to create a file "answer_1.txt" for  
the cases with class==1, and so on, up to "answer_78.txt"

I have been able to do this for one value of "class" in the following  
way

k_1<-answer[class==1]
write.table(k_1, "answer_1.txt")

Now, I would like to loop over "class", replacing the occurences of  
"1" in the code above successively with the integers from 1 to 78, so  
that I get my 78 files.
(equivalent to typing:

k_1<-answer[class==1]
write.table(k_1, "answer_1.txt")

k_2<-answer[class==2]
write.table(k_2, "answer_2.txt")

etc.)

I have tried

for (i in 1:78) k_i<-answer[class==(i)]

but this only generated the variable corresponding to the last value  
(78) of the counter i, and not the files in between.

Thanks a lot for any help or pointers in the right direction. I am an  
R beginner and I studied the help files (they got me up to here), but  
I could not solve this problem on my own.

Chris Kopp



More information about the R-help mailing list