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

From: jim holtman <jholtman_at_gmail.com>
Date: Mon 24 Jul 2006 - 19:41:37 EST

for (i in 1:78){

    write.table(answer[class == i], paste("answer_",i, ".txt", sep=''))     # if you want the variable
    assign(paste("k_", i, sep=''), answer[class == i]) }

On 7/24/06, Chris Kopp <kopp@soz.unibe.ch> wrote:
>
> 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
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?

	[[alternative HTML version deleted]]

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Mon Jul 24 20:34:14 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Mon 24 Jul 2006 - 22:19:54 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.