[R] Loop in columns by group

David Winsemius dwinsemius at comcast.net
Thu Oct 14 05:49:59 CEST 2010


On Oct 13, 2010, at 5:20 PM, Julia Lira wrote:

>
> Dear all,
>
> I need to do a loop as following:
> #Consider a matrix:
>
> M <- matrix(1, nrow=10, ncol=20)
> #Matrices to store the looping results
> M1 <- matrix(0, nrow=10, ncol=400)
> h <- c(1:20/1000)
> #loop
# (I've seen more informative comments)
> for (j in h){
>     M1 <- M/(2*j)
>
> }
>
> But this means that the first 20 columns of matrix M1 (that is,  
> columns 1:20) should show the results of M/(2*0.001).

Why would you think that?

> Then, the following 20 columns of M1 (that is, columns 21:40) should  
> show the results of M/(2*0.002) and so on until columns 381:400 that  
> would show the results of M/(2*0.02).

Dividing a matrix by a scalar produces a matrix of the _same_  
dimensions. You overwrote the M1 matrix 20 times and ended up with the  
results of only the last iteration.

>
> What should I include in the loop above in order to have this result?

Use an indexing strategy that limits the assignment to the particular  
columns targeted.

Perhaps (although I forgot the factor of 2):

for (j in 1:20) {
    M1[ ,(20*j -19):(20*j) <- rep(M1[,j]/h[j], 20) }

 > for (j in 1:20) {
+    M1[ ,(20*j -19):(20*j)] <- rep(M[,j]/h[j], 20) }
 > str(M1)
  num [1:10, 1:400] 1000 1000 1000 1000 1000 1000 1000 1000 1000  
1000 ...

 > M1[1,21]
[1] 500
 > M1[1,41]
[1] 333.3333

-- 
David
>
> Thanks a lot!
>
> Julia
> 		 	   		
> 	[[alternative HTML version deleted]]



More information about the R-help mailing list