How to count TRUE values in a logical vector

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

    There are some problems when logical vector contains NA values.
    See for example:

    z <- c(TRUE, FALSE, NA)
    sum(z) # gives you NA
    table(z)["TRUE"] # gives you 1
    length(z[z == TRUE]) # f3lix answer, gives you 2 (because NA indexing returns values)
    

    So I think the safest is to use na.rm = TRUE:

    sum(z, na.rm = TRUE) # best way to count TRUE values
    

    (which gives 1). I think that table solution is less efficient (look at the code of table function).

    Also, you should be careful with the "table" solution, in case there are no TRUE values in the logical vector. Suppose z <- c(NA, FALSE, NA) or simply z <- c(FALSE, FALSE), then table(z)["TRUE"] gives you NA for both cases.

提交回复
热议问题