Reputation: 1
A<-(FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE)
I want an efficient way to find if A has TRUE and stop when TRUE is found.
Upvotes: 0
Views: 138
Reputation: 6496
My first reaction was thinking about sum(A) != 0
but then went for the microbenchmark
and these are the results:
# install.packages("microbenchmark")
require(microbenchmark)
microbenchmark("sum" = {A <- sample(c(TRUE, FALSE), 1e6, TRUE); sum(A) != 0}, "any" = {A <- sample(c(TRUE, FALSE), 1e6, TRUE); any(A)}, "seq_len" = {A <- sample(c(TRUE, FALSE), 1e6, TRUE); A[seq_len(which(A)[1])]}, times = 100L)
Unit: milliseconds
expr min lq mean median uq max neval
sum 72.98672 75.10716 86.33333 76.88114 78.57807 216.4087 100
any 68.59519 72.35810 78.29730 72.50796 72.83563 229.6932 100
seq_len 80.41055 84.41244 104.30460 87.82726 90.15668 223.8297 100
So definitely any
seems to be the most efficient (other than a Rcpp implementation)
Upvotes: 0
Reputation: 2132
If you just want to know if A
contains any TRUE
values, you can use any()
:
> A <- c(FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE)
> any(A)
[1] TRUE
Upvotes: 2
Reputation: 887058
We can use which
to find the elements that are TRUE, select the first, sequence it and subset the 'A'
A[seq_len(which(A)[1])]
A <- c(FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE)
Upvotes: 1