Skip to content
Prev 381518 / 398502 Next

how to use a matrix as an index to another matrix?

No loops necessary. Use array indexing (see ?"[", of course -- the section
on matrices and arrays)

set.seed(123)
 A <- matrix(sample(1:10), nrow = 5)
 B <- matrix(c(sample(1:5), sample(1:5)), nrow =5, byrow = FALSE)
## The following could be a 1-liner, but I broke it out for clarity.
 ix <- cbind(as.vector(B), rep(1:2, e=5))
 ix
matrix(A[ix], ncol =2)

Cheers,
Bert


Bert Gunter

"The trouble with having an open mind is that people keep coming along and
sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )
On Mon, Oct 28, 2019 at 1:48 PM Linus Chen <linus.l.chen at gmail.com> wrote: