[R] Subsetting a matrix without for-loop

Petr Pikal petr.pikal at precheza.cz
Tue Jan 31 08:38:42 CET 2006


Hi

> matrix(colSums(embed(A,3)[1:3,]),3,6, byrow=T)[3:1,]
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    6   33   60   87  114  141
[2,]    9   36   63   90  117  144
[3,]   12   39   66   93  120  147

will do it. However I am not sure if it is quicker than your for 
loop.

HTH
Petr


On 30 Jan 2006 at 16:29, Camarda, Carlo Giovanni wrote:

Date sent:      	Mon, 30 Jan 2006 16:29:38 +0100
From:           	"Camarda, Carlo Giovanni" <Camarda at demogr.mpg.de>
To:             	<r-help at stat.math.ethz.ch>
Subject:        	[R] Subsetting a matrix without for-loop

> Dear R-users,
> I'm struggling in R in order to "squeeze" a matrix without using a
> for-loop. Although my case is a bit more complex, the following
> example should help you to understand what I would like to do, but
> without the slow for-loop. Thanks in advance, Carlo Giovanni Camarda
> 
> 
> A  <- matrix(1:54, ncol=6)      # my original matrix
> A.new <- matrix(nrow=3, ncol=6) # a new matrix which I'll fill
> # for-loop
> for(i in 1:nrow(A.new)){
>     B <- A[i:(i+2), ]   # selecting the rows
>     C <- apply(B,2,sum) # summing by columns
>     A.new[i,] <- C      # inserting in the new matrix
> }
> 
> 
> +++++
> This mail has been sent through the MPI for Demographic
> Rese...{{dropped}}
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html

Petr Pikal
petr.pikal at precheza.cz




More information about the R-help mailing list