Count TRUE Values in Logical Vector in R (2 Examples)

 

This article shows how to count the number of TRUE values in a logical vector in the R programming language.

The tutorial will consist of two examples for the counting of TRUEs. More precisely, the post looks as follows:

Let’s get started.

 

Example 1: Count TRUEs in Logical Vector in R

In the first example, we’ll use the following logical vector in R:

x1 <- c(FALSE, TRUE, TRUE, FALSE, TRUE)    # Create example vector
x1                                         # Print example vector
# FALSE  TRUE  TRUE FALSE  TRUE

If we want to know the amount of TRUE values of our logical vector, we can use the sum function as follows:

sum(x1)                                    # Sum of example vector
# 3

The RStudio console returns the result: 3 elements of our logical vector are TRUE.

The reason why we can use the sum function is that the sum function automatically converts logical vectors into dummies (i.e. TRUE is converted to 1 and FALSE is converted to 0).

 

Example 2: Handling NA Values in Logical Vector

A typical problem for the counting of TRUEs in a vector are NA values. Consider the following logical vector:

x2 <- c(x1, NA)                            # Crete vector with NA
x2                                         # Print example vector
# FALSE  TRUE  TRUE FALSE  TRUE    NA

As you can see, our new example vector contains an NA value at the end.

If we now apply the sum function as before, an NA is returned:

sum(x2)                                    # sum function returns NA
# NA

Fortunately, the sum function provides the na.rm argument. We can specify na.rm = TRUE in order to exclude all NA values from our analysis:

sum(x2, na.rm = TRUE)                      # Specify na.rm argument
# 3

The result is 3, as in Example 1 – Looks good!

 

Video, Further Resources & Summary

Have a look at the following video of my YouTube channel. In the video, I’m illustrating the examples of this article in a live session:

 

 

In addition, I can recommend to read the other articles of this website. You can find some tutorials below:

 

This article illustrated how to get the amount of positive values in a logical array or vector in R programming. Don’t hesitate to tell me about it in the comments section, if you have additional questions.

 



Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top