简体   繁体   English

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

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

I would like to find the index of the elements in a matrix m that match with a vector v1 and v2 .我想找到矩阵m中与向量v1v2匹配的元素的索引。 So from something similar to res I would like to get element 2 and from res1 get 8. Thank you!所以从类似于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

If order matters so that you want a row to match the order of v1 or v2 exactly then use == instead of %in% .如果顺序很重要以至于您希望一行与v1v2的顺序完全匹配,则使用==而不是%in%

UPdate: Thanks to @Greg pointer!更新:感谢@Greg 指针! We still could use which with == but have to declare the positions of the the vector and matrix elements:我们仍然可以将which==一起使用which但必须声明向量和矩阵元素的位置:

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

First answer (which is not correct in the sense of OP's question)第一个答案(就 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

Try this尝试这个

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

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

Assuming you want order to matter when matching假设您希望在匹配时顺序很重要

          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')

here's an elegant alternative with the native pipe |> that works for an arbitrary number of fields :这是原生管道|>的优雅替代方案,适用于任意数量的字段

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

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

Just make sure you name your columns in the proper order只要确保以正确的顺序命名列

m <- expand.grid(flink, fcor)

such that they correspond to the values in v1 , etc.使它们对应于v1等中的值。

Here's a function in base R to do this -这是基 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

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

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