如何在矩阵 (R) 中查找 row/column 组合的值?
How to look up the value of a row/column combination in a matrix (R)?
我在 R 中有以下查找问题(但我不确定我是否 100% 正确地使用了这个术语)。给定的是一个带有数据点的 matrix
,其中行名和列名相同且顺序相同(例如协方差矩阵)。还给出了 data.frame
行和列名称对,应在矩阵中查找相应的值。
为了说明(并使用非对称矩阵来实现一般性):
set.seed(1)
m = matrix(1:25,5,5)
colnames(m) <- c("A","B","C","D","E")
rownames(m) <- c("A","B","C","D","E")
l <- matrix(ncol=2,nrow=5)
for(i in 1:5){
l[i,] <- sample(c("A","B","C","D","E"),2,replace = FALSE) #choose TRUE if diagonal elements should be included in the list
}
l <- as.data.frame(l)
colnames(l) <- c("row","column")
所以我们有矩阵'm'和data.frame l
(m
和l
的行数相等是巧合,nrow(l)
可能高得多,尽管 >25
肯定会出现冗余对):
A B C D E
A 1 6 11 16 21
B 2 7 12 17 22
C 3 8 13 18 23
D 4 9 14 19 24
E 5 10 15 20 25
row column
1 B E
2 C D
3 B D
4 E C
5 D A
我们寻找一种算法,发现:
> c(22,18,17,15,4)
我很乐意指出如何正确引用此问题以及实际解决方案。
您可以对行名称使用矩阵子集,如下所示:
m[cbind(as.character(l$row), as.character(l$column))]
[1] 22 18 17 15 4
从帮助文件 help("[")
,它说:
关于矩阵子集化:
When indexing arrays by [ a single argument i can be a matrix with as many columns as there are dimensions of x; the result is then a vector with elements corresponding to the sets of indices in each row of i.
此外,关于字符子集:
Character vectors will be matched to the names of the object (or for matrices/arrays, the dimnames).
这两个功能结合起来可以实现您正在寻找的东西。
我在 R 中有以下查找问题(但我不确定我是否 100% 正确地使用了这个术语)。给定的是一个带有数据点的 matrix
,其中行名和列名相同且顺序相同(例如协方差矩阵)。还给出了 data.frame
行和列名称对,应在矩阵中查找相应的值。
为了说明(并使用非对称矩阵来实现一般性):
set.seed(1)
m = matrix(1:25,5,5)
colnames(m) <- c("A","B","C","D","E")
rownames(m) <- c("A","B","C","D","E")
l <- matrix(ncol=2,nrow=5)
for(i in 1:5){
l[i,] <- sample(c("A","B","C","D","E"),2,replace = FALSE) #choose TRUE if diagonal elements should be included in the list
}
l <- as.data.frame(l)
colnames(l) <- c("row","column")
所以我们有矩阵'm'和data.frame l
(m
和l
的行数相等是巧合,nrow(l)
可能高得多,尽管 >25
肯定会出现冗余对):
A B C D E
A 1 6 11 16 21
B 2 7 12 17 22
C 3 8 13 18 23
D 4 9 14 19 24
E 5 10 15 20 25
row column
1 B E
2 C D
3 B D
4 E C
5 D A
我们寻找一种算法,发现:
> c(22,18,17,15,4)
我很乐意指出如何正确引用此问题以及实际解决方案。
您可以对行名称使用矩阵子集,如下所示:
m[cbind(as.character(l$row), as.character(l$column))]
[1] 22 18 17 15 4
从帮助文件 help("[")
,它说:
关于矩阵子集化:
When indexing arrays by [ a single argument i can be a matrix with as many columns as there are dimensions of x; the result is then a vector with elements corresponding to the sets of indices in each row of i.
此外,关于字符子集:
Character vectors will be matched to the names of the object (or for matrices/arrays, the dimnames).
这两个功能结合起来可以实现您正在寻找的东西。