Search code examples
rbinaryvectorizationlogical-operatorsprocessing-efficiency

Quickly combine logical matrices with & in R


I have a large logical matrix and need to combine each column with a vector using the & operation. Right now I'm looping over the columns but this takes a while since there are over 1 million rows. Is there faster, possibly vectorized way to do this?

mx <- replicate(10, sample(c(T,F), size = 1000, replace = T)) # 1000 rows x 10 columns
bool <- sample(c(T,F), size = 1000, replace = T) # 1000 elements

out <- apply(mx1, 2, function(x) {
  x & bool
})

For context, this data is from a gene expression matrix where 1 row = 1 cell


Solution

  • Easy in this case:

    mx & bool
    

    bool is recycled for all the columns in mx

    identical(mx & bool, out)
    

    output:

    [1] TRUE