[R] for() loop

David Freedman 3.14david at gmail.com
Mon Mar 15 12:20:47 CET 2010


Hi - do you want 

sum(datjan$V4)
     OR
sum(unique(datjan$V4))  ?

there's also a cumsum function that might be useful

hth, 
David Freedman, Atlanta




Schmidt Martin wrote:
> 
> Hello
> 
> I'm working with R since a few month and have still many trivial  
> questions - I guess! Here is what I want:
> 
> I have this matrix:
>> dim(datjan)
> [1] 899   4
> 
> The first 10 rows looks as follows:
>> datjan[1:10,]
>       V1 V2 V3 V4
> 1  1961  1  1 24
> 2  1961  1  2 24
> 3  1961  1  3 24
> 4  1961  1  4 24
> 5  1961  1  5 24
> 6  1961  1  6 27
> 7  1961  1  7 27
> 8  1961  1  8 27
> 9  1961  1  9 27
> 10 1961  1 10 27
> 
> I tried now to create a for() loop, which gives me the sum of the 30  
> different classes (1:30!) in [,4].
> 
> for(i in 1:30){
> sum(datjan[,4]==i)
> }
> 
> R is then actually calculating the sum of "i" which certainly doesn't  
> exist and results in a "0" value
> 
> t1<-sum(datjan[,4]==1)
> t2<-sum(datjan[,4]==2)
> .................................until '30'
> This way its working, but I won't find a end by doing all this by  
> hand, because there are many other matrix waiting.
> 
> So, how can I make work that loop??
> 
> thanks for helping me
> 
> ______________________________________________
> R-help at r-project.org 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.
> 
> 
-- 
View this message in context: http://n4.nabble.com/for-loop-tp1592713p1593235.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list