如何获取矩阵中与向量值匹配的元素的索引

How to get the index of elements in a matrix that match values of a vector

我想找到矩阵 m 中与向量 v1v2 匹配的元素的索引。因此,从类似于 res 的内容中,我想获取元素 2 并从 res1得到8个。谢谢!

flink = c("logit", "probit", "GEVmodNS", "GEVmod")
fcor = c("tanimoto", "exponential", "gaussian", "independent")
v1 = c('logit', 'exponential')
v2 = c('probit', 'independent')
m = expand.grid(fcor,flink)
res = m %in%v1
res1 = m %in%v2
which(apply(m, 1, function(x) all(x %in% v1)))
[1] 2

which(apply(m, 1, function(x) all(x %in% v2)))
[1] 8

如果顺序很重要,因此您希望一行与 v1v2 的顺序完全匹配,则使用 == 而不是 %in%

更新:感谢@Greg 指点! 我们仍然可以将 which== 一起使用,但必须声明向量和矩阵元素的位置:

> which(m[,1] == v1[2] & m[,2] == v1[1])
[1] 2
> which(m[,1] == v2[2] & m[,2] == v2[1])
[1] 8

第一个答案(从 OP 的问题来看这是不正确的)

which(v1 == m)
which(v2 == m)
> which(v1 == m)
[1]  2  6 10 14 17 19
> which(v2 == m)
[1]  4  8 12 16 21 23

试试这个

> which(!lengths(Map(setdiff, list(v1), asplit(m, 1))))
[1] 2

> which(!lengths(Map(setdiff, list(v2), asplit(m, 1))))
[1] 8

假设您希望在匹配时顺序重要

          Var2           Var1
   1     logit       tanimoto
   2     logit    exponential
#         ...           ...

# Should match row 2.
v1 <- c('logit', 'exponential')

# Should NOT match row 2.
v3 <- c('exponential', 'logit')

这是原生管道 |> 的优雅替代方案,适用于 任意数量的字段 :

(v1 == t(m)) |> apply(2, all) |> which()
# [1] 2

(v2 == t(m)) |> apply(2, all) |> which()
# [1] 8

只需确保以正确的顺序命名列

m <- expand.grid(flink, fcor)

使得它们对应于 v1 中的值,等等

这是 R 基础中的一个函数来执行此操作 -

match_a_row <- function(data, var1, var2) {
  which(data[[1]] == var1 & data[[2]] == var2)
}

match_a_row(m, 'exponential', 'logit')
#[1] 2
match_a_row(m, 'independent', 'probit')
#[1] 8