How to count TRUE values in a logical vector

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

    which is good alternative, especially when you operate on matrices (check ?which and notice the arr.ind argument). But I suggest that you stick with sum, because of na.rm argument that can handle NA's in logical vector. For instance:

    # create dummy variable
    set.seed(100)
    x <- round(runif(100, 0, 1))
    x <- x == 1
    # create NA's
    x[seq(1, length(x), 7)] <- NA
    

    If you type in sum(x) you'll get NA as a result, but if you pass na.rm = TRUE in sum function, you'll get the result that you want.

    > sum(x)
    [1] NA
    > sum(x, na.rm=TRUE)
    [1] 43
    

    Is your question strictly theoretical, or you have some practical problem concerning logical vectors?

提交回复
热议问题