Take the following matrix for example, I want to find the array indices of some values.
set.seed(123)
mat <- matrix(sample(1:5, 15, TRUE), 5, 3)
# [,1] [,2] [,3]
# [1,] 3 5 5
# [2,] 3 4 3
# [3,] 2 1 3
# [4,] 2 2 1
# [5,] 3 3 4
If it's a single value, say 2, then I can use which(..., arr.ind = TRUE) to find the coordinates.
which(mat == 2, arr.ind = TRUE)
# row col
# [1,] 3 1
# [2,] 4 1
# [3,] 4 2
However, if I want to find the positions matched to a set of values, say c(1, 2), the code gives me a vector indices.
which(mat %in% 1:2, arr.ind = TRUE)
# [1] 3 4 8 9 14
How could I transform it to an 2-column form that indicate rows and columns from the matrix?