How do I effectively combine logical vectors across the list using elementwise comparisons with logical OR
(|
). The result should be a logical vector of same length as the input vectors. If any of the input values is TRUE
, the result is TRUE
, else the result is FALSE
.
I have a list opts with a set of logical vectors of the same length.
> str(opts)
List of 5
$ option1: logi [1:608247] FALSE FALSE FALSE FALSE FALSE FALSE ...
$ option2: logi [1:608247] FALSE TRUE FALSE TRUE TRUE TRUE ...
$ option3: logi [1:608247] FALSE TRUE FALSE FALSE TRUE FALSE ...
$ option4: logi [1:608247] FALSE FALSE FALSE FALSE FALSE FALSE ...
and I want this as a result:
logi [1:608247] FALSE TRUE FALSE TRUE TRUE TRUE ...
Thus, the first value of the result, FALSE
, is because the are no TRUE
in the first position across all vectors of the list. The second value of the result, TRUE
, is because the are two (at least one, any
) TRUE
in the second position of the vectors.
I am fine with changing my datastructure to be a matrix
or data.frame
or something else if it is better I just get this from a lapply
.
Logical operators combine relations according to the following rules: The ampersand (&) symbol is a valid substitute for the logical operator AND . The vertical bar ( | ) is a valid substitute for the logical operator OR . Only one logical operator can be used to combine two relations.
A logical vector is a vector that only contains TRUE and FALSE values. In R, true values are designated with TRUE, and false values with FALSE. When you index a vector with a logical vector, R will return values of the vector for which the indexing vector is TRUE.
Details. TRUE and FALSE are reserved words denoting logical constants in the R language, whereas T and F are global variables whose initial values set to these. All four are logical(1) vectors.
How about Reduce:
Reduce("&", opts)
Reduce("|", opts)
If all the lists are the same length, you can cast it to a data frame, and then use any
:
apply(data.frame(opts),1,any)
Edit: while I thought this might be fast because it avoids cbind
, it turns out that this is the slowest by far of the three solutions, according to my benchmarking:
set.seed(123)
opts = as.list(as.data.frame(matrix(sample(c(TRUE, FALSE), 10000, replace=TRUE), nrow=1000)))
require(microbenchmark)
microbenchmark(Reduce("|",opts),rowSums(do.call(cbind, opts)) > 0,
apply(as.data.frame(opts),1,any))
Unit: microseconds
expr min lq median uq
Reduce("|", opts) 99.200 101.0780 106.596 110.3725
rowSums(do.call(cbind, opts)) > 0 209.326 211.9665 217.329 224.0505
apply(as.data.frame(opts), 1, any) 4130.429 4245.7380 4308.054 4438.2485
max neval
120.63 100
237.19 100
6949.19 100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With