[R] For Loops

Sundar Dorai-Raj doraiss at auburn.edu
Tue Oct 30 18:17:12 CET 2001


Why not use tapply?

tapply(data,data$id,function(x) x)

This will split the data up according to id then allow you to apply a
function to each subset. This would be identical to, but more efficient
than, the following:

for(i in 1:n) {
  subset <- data[which(data$id==i),]
  f(subset) # where f() is sum function applied to the subset
}

Hope this helps.

Sundar



> -----Original Message-----
> From: owner-r-help at stat.math.ethz.ch 
> [mailto:owner-r-help at stat.math.ethz.ch] On Behalf Of Isabel Jones
> Sent: Tuesday, October 30, 2001 8:19 AM
> To: r-help at hypatia.math.ethz.ch
> Subject: [R] For Loops
> 
> 
> Hi all
> 
> Perhaps someone could help me?
> 
> I am running a loop from i=1 to n
> 
> In my data.frame I have a list of i.d's (i=1 to n) and
> each i.d has 2
> rows of data (representing 2 time points) e.g.
> 
> id  Y   X1   X2
>  1   1   0     0 
>  1   0   0     0
>  2   1   1     0
>  2   1   1     0
> 
> I am wanting to put into my 'for' loop, a line which
> can pick out the
> rows where id=i and call this a temporary name while
> it executes some
> commands beforing moving on to the next i. I'm not
> sure what command I
> can use to locate these rows where id=i and store them
> in a temporary
> matrix.
> 
> Also when I have say a matrix consisting of all values
> of Y - how can I
> refer to the Y for person i i.e. Yi
> I have seen in the R information that I can use
> Y[[i]]?
> Is it possible to write say Y[[i]]<-x[[i]]*5
> 
> Can somebody point me in the right direction as to how
> to use indexing?
> 
> Cheers to all
>    Isabel
> 
> __________________________________________________
> 
> 
> 
> -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
> -.-.-.-.-.-.-.-.-
> r-help mailing list -- Read 
> http://www.ci.tuwien.ac.at/~hornik/R/R-> FAQ.html
> Send "info", 
> "help", or "[un]subscribe"
> (in the 
> "body", not the subject !)  To: 
> r-help-request at stat.math.ethz.ch 
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._.
> _._._._._._._._._
> 

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list