l0110
l0110

Reputation: 899

Extract specific elements in a matrix with a character vector in R

I want to extract specific elements column wise from the matrix A with the information from a character vector B (contain elements in the row names of the matrix) such as:

A <- matrix(seq(1,12),ncol=4)
rownames(A) <- letters[1:3]

A
  [,1] [,2] [,3] [,4]
a    1    4    7   10
b    2    5    8   11
c    3    6    9   12

B <- c("a","c","c","b")

I want to get 1,6,9,11. Thanks :)

Upvotes: 0

Views: 101

Answers (1)

mt1022
mt1022

Reputation: 17299

Two possible ways:

> A[cbind(match(B, rownames(A)), seq_len(ncol(A)))]
[1]  1  6  9 11
> 
> diag(A[B, seq_along(B)]) # or diag(A[B, seq_len(ncol(A))])
[1]  1  6  9 11

Upvotes: 1

Related Questions