You can use the following methods to count the number of TRUE values in a logical vector in R:
Method 1: Use sum()
sum(x, na.rm=TRUE)
This method will return the count of TRUE values in a vector.
Method 2: Use summary()
summary(x)
This method will return the count of TRUE, FALSE, and NA values in a vector.
The following examples show how to use each method in practice.
Example 1: Count TRUE Values Using sum()
The following code shows how to use sum() to count the number of TRUE values in a logical vector:
#create logical vector x #count TRUE values in vector sum(x, na.rm=TRUE) [1] 3
From the output we can see that there are 3 TRUE values in the vector.
Note: If there are NA values in the vector and we don’t use the argument na.rm=TRUE, then the function will return NA.
Example 2: Count TRUE Values Using summary()
The following code shows how to use summary() to count the number of TRUE, FALSE, and NA values in a logical vector:
#create logical vector
x #count TRUE, FALSE, and NA values in vector
summary(x)
Mode FALSE TRUE NA's
logical 4 3 1
From the output we can see:
- There are 4 FALSE values in the vector.
- There are 3 TRUE values in the vector.
- There is 1 NA value in the vector.
The summary() function is particularly useful if you’d like to know the occurrence of each type of value in a logical vector.
If you’d like to only return the number of TRUE values from the summary() function, you can use the following syntax:
#create logical vector x #count TRUE values in vector summary(x)['TRUE'] TRUE 3
From the output we can see that there are 3 TRUE values in the vector.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Count Values in Column with Condition in R
How to Count Observations by Group in R
How to Select Top N Values by Group in R