Alex Rivera | Logout

How to count TRUE values in a logical vector

Asked 2010-02-03T09:03:38.140
205

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(TRUE, FALSE), 1000, rep = TRUE)
sum(z)
# [1] 498

table(z)["TRUE"]
# TRUE 
#  498 

Which do you prefer? Is there anything even better?

r
Edit
Report

1 Answer

6

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?

answered 2010-02-05T02:02:28.693

Your Answer