Count Elements that Satisfy a Logical Condition in R (2 Examples)

 

This page demonstrates how to get the number of elements that satisfy a logical condition in the R programming language.

The tutorial will consist of the following content:

Sound good? Let’s dive into it…

 

Introducing Example Data

The first step is to define some data that we can use in the examples later on:

my_x <- 1:10                  # Create vector object
my_x                          # Print vector object
#  [1]  1  2  3  4  5  6  7  8  9 10

The previous output of the RStudio console reveals the structure of our example data – We have created a vector object containing ten different numeric values.

Next, we can use logical operators to test which entries of our vector object satisfy a logical condition:

my_cond <- my_x >= 6          # Test logical condition
my_cond                       # Print output
#  [1] FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE

The previous R syntax has returned a vector of TRUE and FALSE values.

 

Example 1: Count Elements that Satisfy a Condition Using sum() Function

The following code illustrates how to check how many elements satisfy a logical condition.

For this task, we can apply the sum function to our vector of TRUE and FALSE values:

sum(my_cond)                  # Count elements that satisfy condition
# [1] 5

The previous output shows that five elements of our TRUE and FALSE vector are equal to TRUE, i.e. five elements satisfy the logical condition that we have tested in the previous section.

 

Example 2: Count Elements that Satisfy a Condition Using length() & which() Functions

In this example, I’ll illustrate how to use the length and which functions to check how many elements in a vector satisfy a condition.

Consider the R code below:

length(which(my_cond))        # Count elements that satisfy condition
# [1] 5

As you can see, the previous R syntax has returned the same result as the code in Example 1.

 

Video & Further Resources

Do you need more info on the R programming syntax of this article? Then I recommend having a look at the following video tutorial on my YouTube channel. In the video, I’m explaining the R programming codes of this tutorial:

 

 

In addition to the video, you might have a look at the related tutorials on Statistics Globe:

 

In this tutorial, I have shown how to count the elements that satisfy a condition in R. Please let me know in the comments, if you have any further questions.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


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.

Top