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

From: Uwe Ligges <ligges_at_statistik.uni-dortmund.de>
Date: Thu 08 Jul 2004 - 21:21:53 EST

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@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



R-help@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 Received on Thu Jul 08 21:29:52 2004

This archive was generated by hypermail 2.1.8 : Wed 03 Nov 2004 - 22:54:46 EST