[R] For Loops
kjetil halvorsen
kjetilh at umsanet.edu.bo
Tue Oct 30 18:39:30 CET 2001
Hola!
fr <- data.frame(id=c(1,1,2,2,3,3,4,4), x=rnorm(8), y=rnorm(8))
> for (i in 1:4) { temp <- fr[fr$id==i,]
+ print(temp)}
id x y
1 1 -1.817315 -0.940551
2 1 1.511910 1.306569
id x y
3 2 -1.3677349 0.5242760
4 2 0.4932293 0.4221455
id x y
5 3 0.0975871 -1.6131919
6 3 0.1439102 -0.4736377
id x y
7 4 0.4927572 1.2780839
8 4 0.3018717 -0.8101557
>
for the second Q I think you want something like
Y[i,]
not Y[[i]] --- that is for lists.
Kjetil Halvorsen
Isabel Jones wrote:
>
> 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