The all.equal
function gives you the result you want. I did not use the mat
of your example because my computer, even with the seed set, generates random numbers different from yours. So I created a new array with well-defined values.
mat <- matrix(1:50, ncol=5)
vec1 <- c(1, 2, 3, 4, 5)
vec2 <- c(1, 11, 21, 31, 41)
vec3 <- c(5, 15, 25, 35, 45)
which(apply(mat, 1, function(x) all.equal(x, vec1)) == "TRUE")
integer(0)
which(apply(mat, 1, function(x) all.equal(x, vec2)) == "TRUE")
[1] 1
which(apply(mat, 1, function(x) all.equal(x, vec3)) == "TRUE")
[1] 5
What the all.equal
function does is compare two objects in R
to see if they are fairly equal. The good thing about this function is that it has an argument called tolerance
(which I use below) to solve just the tolerance problem that can appear in your simulations.
Using apply
, I can apply the all.equal
function to all rows in the array, without requiring a loop.
Here is a function suggestion to reproduce this result:
linha <- function(matriz, vetor){
aux <- which(apply(matriz, 1, function(matriz) all.equal(matriz, vetor, tolerance=1e-5)) == "TRUE")
if (length(aux) > 0){
resposta <- aux
} else {
resposta <- "nao existe"
}
return(resposta)
}
linha(mat, vec1)
[1] "nao existe"
linha(mat, vec2)
[1] 1
linha(mat, vec3)
[1] 5
To find out if at least one element of the array is in the array, use a code similar to the one above, but without the function all.equal
:
which(apply(mat, 1, function(x) x == vec1))
[1] 1
which(apply(mat, 1, function(x) x == vec2))
[1] 1 2 3 4 5
which(apply(mat, 1, function(x) x == vec3))
[1] 21 22 23 24 25
So you'll know exactly what mat
positions have elements of vec
.