How to count TRUE values in a logical vector

后端 未结 8 1593
[愿得一人]
[愿得一人] 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 02:08

    Another way is

    > length(z[z==TRUE])
    [1] 498
    

    While sum(z) is nice and short, for me length(z[z==TRUE]) is more self explaining. Though, I think with a simple task like this it does not really make a difference...

    If it is a large vector, you probably should go with the fastest solution, which is sum(z). length(z[z==TRUE]) is about 10x slower and table(z)[TRUE] is about 200x slower than sum(z).

    Summing up, sum(z) is the fastest to type and to execute.

提交回复
热议问题