[R] Extracting from a matrix w/o for-loop

Horace Tso Horace.Tso at pgn.com
Fri Jul 28 19:21:25 CEST 2006

Unless there is another level of complexity that i didn't see here,
wouldn't it be a simply application of sapply as follow,

sapply( 1:dim(M2)[[1]], function(x) M1[M2[x,1], M2[x,2]] )

Hope this helps.


>>> "Camarda, Carlo Giovanni" <Camarda at demogr.mpg.de> 7/28/2006 9:40 AM
Dear R-users,

likely there is a simple solution for this problem, but I currently
cannot see it.

I basically would like to get from a matrix values in particular
positions which are the rows of another matrix, without using a

In other words: is there any way to avoid the for-loop in the
simple example:

M1 <- matrix(1:20, ncol=2)
M2 <- rbind(c(1,1), c(2,1), c(3,2), c(5,2), c(8,1))
v <- numeric(nrow(M2))
for(i in 1:length(v)){
    v[i] <- M1[M2[i,1], M2[i,2]]

Any suggestion would be welcome,

Carlo Giovanni Camarda

Camarda Carlo Giovanni
Max Planck Institute for Demographic Research
Konrad-Zuse-Strasse 1
18057 Rostock, Germany
Tel:  +49 (0)381 2081 172
Fax: +49 (0)381 2081 472
camarda at demogr.mpg.de 

This mail has been sent through the MPI for Demographic

R-help at stat.math.ethz.ch mailing list
PLEASE do read the posting guide
and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list