[R] Getting elements of a matrix by a vector of column indices

Uwe Ligges ligges at statistik.uni-dortmund.de
Thu Jul 8 13:21:53 CEST 2004


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




More information about the R-help mailing list