Reputation: 301
How to construct a function that evaluates if any line of matrix mat
is equal to vector vec
in code below:
set.seed(000)
mat <- matrix(rnorm(20),4,5)
vec <- c(1.3297993, -0.9285670, 0.7635935, -0.2992151, 0.4356833)
mat[3,]
vec
mat==vec
Also, how determine if at least one vec
value is in mat
?
Note: mat == vec
should be equal to TRUE
, ie mat-vec == 0
if mat-vec <tol
, where tol = 1e-5
.
Upvotes: 1
Views: 261
Reputation: 534
First of all, your example won't work because of the floating point trap (starting on page 9).
This should do the trick:
set.seed(000)
mat <- round(matrix(rnorm(20),4,5), digits = 7)
vec <- c(1.3297993, -0.9285670, 0.7635935, -0.2992151, 0.4356833)
Now, mat[3, ] == vec
is true.
If you want to know if one row of mat
matches vec
, try:
apply(mat, 1, function(x) identical(x, vec))
To find out if at least one value of vec
is in mat
, you can do:
length(vec[which(vec %in% mat)])
The result reflects the number of matches found between your vector and your matrix.
Upvotes: 3
Reputation: 57686
Something like this:
compare <- function(mat, vec, tol=1e-5)
{
ok <- apply(mat, 1, function(v) {
all(abs(v - vec) < tol)
})
any(ok)
}
v <- 1:5
m <- matrix(rnorm(25), nrow=5)
compare(m, v)
# FALSE
m[1,] <- v
compare(m, v)
# TRUE
Upvotes: 2