简体   繁体   English

使用 R 中的字符向量提取矩阵中的特定元素

[英]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 中提取特定元素的列,其中包含来自字符向量 B 的信息(包含矩阵行名中的元素),例如:

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.我想得到 1,6,9,11。 Thanks:)谢谢:)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM