In R, what is the most efficient/idiomatic way to count the number of TRUE
values in a logical vector? I can think of two ways:
z <- sample(c
There's also a package called bit
that is specifically designed for fast boolean operations. It's especially useful if you have large vectors or need to do many boolean operations.
z <- sample(c(TRUE, FALSE), 1e8, rep = TRUE)
system.time({
sum(z) # 0.170s
})
system.time({
bit::sum.bit(z) # 0.021s, ~10x improvement in speed
})