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

Time:10-29

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

Try this

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

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

CodePudding user response:

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.

  • Related