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

2004-07-08 Thread Wolfram Fischer
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

__
[EMAIL PROTECTED] 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


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

2004-07-08 Thread Uwe Ligges
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
__
[EMAIL PROTECTED] 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
__
[EMAIL PROTECTED] 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