简体   繁体   English

如何使用row.name和col.name的几个子集矩阵

[英]How to subset matrix with couples of row.name and col.name

I have a simple problem. 我有一个简单的问题。 I have a data frame with two columns of character variables, corresponding to row and column name "couples" from a separate matrix. 我有一个带有两列字符变量的数据框,对应于来自单独矩阵的行和列名称“couple”。 I just want to use those couples to look up values in the matrix, returned in a vector. 我只是想用这些夫妇在矩阵中查找值,并在向量中返回。

I'm sure it is trivial, but I haven't been able to come across an answer in over an hour of googling. 我确信这是微不足道的,但我在一个多小时的谷歌搜索中找不到答案。 Here is a reproducible example: 这是一个可重复的例子:

m <- as.matrix(data.frame(a=c(1,2,3,4), 
                          b=c(14,15,16,17), 
                          c=c(27,28,29,30), 
                          d=c(43,44,45,46)))
row.names(m) <- c('w','x','y','z')

df <- data.frame(j=c('x','z','z','w','x'),
                 k=c('a','b','d','d','c'))

#I just want to "lookup" a vector of values equal to c(2,17,46,43,28)
result <- sapply(df, function(x) m[x[1],x[2]])

result
j.c k.b 
28  14

Can someone help me figure this out? 有人可以帮我解决这个问题吗? sapply may not be the best approach, and I'm open to other ideas. sapply可能不是最好的方法,我对其他想法sapply开放态度。

Just coerce the data.frame to be a matrix and use it as index 只需将data.frame强制为matrix并将其用作索引

> m[as.matrix(df)]
[1]  2 17 46 43 28

Take a look at this document to realize why this works. 看看这个文档 ,了解为什么会这样。

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

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