How to count TRUE values in r
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?
To count TRUE in r values in a logical vector, you can use the following functions:
z <- sample(c(TRUE, FALSE), 10000, rep = TRUE)
length(z[z== TRUE])
[1] 5095
sum(z)
[1] 5095
table(z)["TRUE"]
TRUE
5095
In vector where there are NA values:
z <- sample(c(TRUE, FALSE,NA), 10000, rep = TRUE)
sum(z, na.rm = TRUE)
[1] 3265
table(z)["TRUE"]
TRUE
3265
The length function counts the return value of NA’s as a TRUE value.
length(z[z== TRUE])
[1] 6671
In vectors having no TRUE values:
sum(z, na.rm = TRUE)
[1] 0
length(z[z== TRUE]) #Counts return values of NA as TRUE
[1] 5004
table(z)["TRUE"] #Returns NA
NA
So the best solution to count TRUE values is to use the sum() function along with the na.rm argument as TRUE.