How to count TRUE values in a logical vector

后端 未结 8 1576
[愿得一人]
[愿得一人] 2020-11-28 01:17

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         


        
8条回答
  •  粉色の甜心
    2020-11-28 01:55

    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
    })
    

提交回复
热议问题