Wolfram Fischer
2004-Jul-08 09:58 UTC
[R] Getting elements of a matrix by a vector of column indices
I have e.g. t <- matrix( nrow=2, ncol=3, byrow=TRUE, c('a1','a2','a3','b1','b2','b3') ) and i <- c( 3, 2) Is it possible to formulate a simple expression that gets c( t[ 1, i[1] ], t[ 2, i[2] ] ) (and so on for longer matrices)? The result would be: [1] "a3" "b2" Thanks - Wolfram
Uwe Ligges
2004-Jul-08 11:21 UTC
[R] Getting elements of a matrix by a vector of column indices
Wolfram Fischer wrote:> I have e.g. > t <- matrix( nrow=2, ncol=3, byrow=TRUE, c('a1','a2','a3','b1','b2','b3') ) > and > i <- c( 3, 2) > > Is it possible to formulate a simple expression that gets > c( t[ 1, i[1] ], t[ 2, i[2] ] ) > (and so on for longer matrices)? > > The result would be: > [1] "a3" "b2" >Two solutions are (there might be better ones): a) mapply(function(x,y) t[x,y], 1:nrow(t), i) b) t(t)[i + (1:nrow(t) - 1) * (ncol(t))] Note that calling the matrix "t" is not the best idea. Uwe Ligges> Thanks - Wolfram > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > https://www.stat.math.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html