The function all.equal
gives the result you want. I did not use the mat
of your example because my computer, even with the adjusted seed, generates random numbers different than yours. So I created a new matrix 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 function all.equal
is to compare two objects in the R
to see if they are reasonably equal. The good thing about this function is that it has an argument called tolerance
(that I use below) to solve precisely the problem of tolerance that may appear in your simulations.
Using the apply
, I can apply the function all.equal
to all rows of the matrix, without needing a loop.
Below is a suggested function to play 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 vector element is in the matrix, 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 positions mat
which contain elements of vec
.