# Subsetting a matrix without for-loop

4 messages
Open this post in threaded view
|

## 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}} ______________________________________________ [hidden email] mailing list https://stat.ethz.ch/mailman/listinfo/r-helpPLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Open this post in threaded view
|

## Re: Subsetting a matrix without for-loop

 The result is linear in A so its a matter of finding the matrix to multiply it by:  matrix(c(rep(1,3), rep(0,7)), 3, 9, byrow = TRUE) %*% A On 1/30/06, Camarda, Carlo Giovanni <[hidden email]> wrote: > 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}} > > ______________________________________________ > [hidden email] mailing list > https://stat.ethz.ch/mailman/listinfo/r-help> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html> ______________________________________________ [hidden email] mailing list https://stat.ethz.ch/mailman/listinfo/r-helpPLEASE do read the posting guide! http://www.R-project.org/posting-guide.html