I want to find a quick way to see if a matrix M has at least one value that is, say, 2. In R, I would use any(M==2). However, this computes first M==2 for all values in M, then use any(). any() will stop at the first time a TRUE value is found, but that still means we computed way too many M==2 conditions.
I thought one could find a more efficient way, computing M==2 only as long as it is not satisfied. I tried to write a function to do this (either column-wise check, or on each element of M, check_2), but it is so far much slower. Any idea on how to improve this?
Results of benchmark, where the value Val is rather at the end of the matrix:
|expr |mean time |
|:------------------|---------:|
|any(M == Val) | 14.13623|
|is.element(Val, M) | 17.71230|
|check(M, Val) | 18.20764|
|check_2(M, Val) | 486.65347|
Code:
x <- 1:10^6
M <- matrix(x, ncol = 10, byrow=TRUE)
Val <- 50000
check <- function(x, Val) {
i <- 1
cond <- FALSE
while(!cond & i <= ncol(x)) {
cond <- any(M[,i]==Val)
i <- i +1
}
cond
}
check_2 <- function(x, Val) {
x_c <- c(x)
i <- 1
cond <- FALSE
while(!cond & i <= length(x_c)) {
cond <- x_c[i]==Val
i <- i +1
}
cond
}
check_2(x=M, Val)
check(M, Val)
library(microbenchmark)
comp <- microbenchmark(any(M == Val),
is.element(Val, M),
check(M, Val),
check_2(M, Val),
times = 20)
comp
check()if yourValis found in the last column. But it makes a different, for example, withVal <- 1. \$\endgroup\$