To count TRUE 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>
NA
So the best solution to count TRUE values is to use the sum() function along with the na.rm argument as TRUE.
If you want to learn more about R programming watch this tutorial on Introduction to Data Science with R