[R] How to extract from a matrix based on indices in a vector?
David Winsemius
dwinsemius at comcast.net
Thu Jun 11 02:30:14 CEST 2009
On Jun 10, 2009, at 1:36 PM, Logickle wrote:
>
> Sorry, there may be some lingo for describing the extraction problem
> I have,
> but I don't know it.
>
> I have a matrix of 2 rows and N columns, and a vector of N 1s and 2s.
>
> Matrix M:
>
> 1 2 3 4 ... N
> 1 A C D G ...
> 2 B D F H ...
>
> Vector v:
>
> 1 2 2 1 2 1 1 ... N
>
> I'd like to apply v to M to get
>
> Vector w:
>
> A D F G ...
Using length 10 M and v
> w <- apply(cbind(v, 1:length(v) ), 1, function(x) M[x[1], x[2] ])
[1] "A" "D" "F" "G" "I" "K" "N" "P" "R" "S"
> M <- matrix(LETTERS[1:20], nrow=2)
> M
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] "A" "C" "E" "G" "I" "K" "M" "O" "Q" "S"
[2,] "B" "D" "F" "H" "J" "L" "N" "P" "R" "T"
> v <- c(1,2,2,1, sample(1:2, 6, replace=TRUE) )
> v
[1] 1 2 2 1 1 1 2 2 2 1
The number of rows in M should not be a problem.
>
> I.e. each element of v is interpreted as a row-index used to extract
> that
> row's value from the corresponding column in M into the
> corresponding column
> of w.
>
> Also eventually nrow(M) > 2, in which case the value of the elements
> of v
> would range over 1:nrow(M).
>
> Seems it should be simple, but maybe not?
Seems reasonably simple.
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
More information about the R-help
mailing list