简体   繁体   中英

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 . So from something similar to res I would like to get element 2 and from res1 get 8. Thank you!

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% .

UPdate: Thanks to @Greg pointer! We still could use which with == but have to declare the positions of the the vector and matrix elements:

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

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.

Here's a function in base R to do this -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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