[R] change codes into loops

David Winsemius dwinsemius at comcast.net
Tue Jan 19 01:58:06 CET 2010


On Jan 18, 2010, at 7:19 PM, rusers.sh wrote:

> Hi,
>  See example.
>   for (i in 1:2) {
>  for (j in 1:3) {
>     b_1[i,j]<-rank(c(a1[i,j],a2[i,j],a3[i,j]))[1]
>    b_2[i,j]<-rank(c(a1[i,j],a2[i,j],a3[i,j]))[2]
>     b_3[i,j]<-rank(c(a1[i,j],a2[i,j],a3[i,j]))[3]
>  }
> }
>  The inner codes is really repeated, so i want to change the inner  
> codes
> into loops. Take nn is from 1 to 3,
> something like,
>  for (nn in 1:3) {
> b_nn[i,j]<-rank(c(a1[i,j]:a3[i,j]))[nn]
> }
>  Anybody can tell me the correct method to specify the above codes?

There is no correct method. You cannot index on the object name b_nn  
that way. R has not been developing using a syntax with that much  
flexibility.  If you want a 3D array of values, then you could create  
b_ijn[i, j, nn] and make assignments to it. But if you tried to do  
this with paste and assign, you will spending considerably more time  
degbugging it than it is worth and it would likely be more inefficient  
than what you have.

-- 
David.

> Thanks.
>
> -- 
> -----------------
> Jane Chang
> Queen's
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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.

David Winsemius, MD
Heritage Laboratories
West Hartford, CT



More information about the R-help mailing list