R Equivalent to COUNTIF in Excel (Example)

 

This page shows how to realize Excel’s COUNTIF function in the R programming language.

The page will consist of the following:

If you want to know more about these topics, keep reading.

 

Creation of Example Data

The data below will be used as basement for this R tutorial:

x <- c("a", "c", "d", "c", "b", "b", "c")    # Create example vector
x                                            # Print example vector
# [1] "a" "c" "d" "c" "b" "b" "c"

The previous output of the RStudio console shows the structure of our example data: It’s a character vector containing several elements.

 

Example: Applying Equivalent to Excel’s COUNTIF in R Using == Operator & sum() Function

In this example, I’ll illustrate how to execute R’s counterpart to the COUNTIF function in Microsoft Excel.

Let’s start by replicating Excel’s IF statement in R. For this, we simply have to use the == operator:

x == "c"                                     # Equivalent to Excel's IF
# [1] FALSE  TRUE FALSE  TRUE FALSE FALSE  TRUE

The previous R code has returned a logical vector to the RStudio console, indicating which elements of our data are equal to the letter “c”.

We can now wrap the sum function around this code to get the equivalent of COUNTIF:

sum(x == "c")                                # Equivalent to Excel's COUNTIF
# [1] 3

The RStudio console has returned the numerical value 3, i.e. the letter “c” occurs three times in our example data.

Note that we could apply the same kind of R code to a data frame column as well.

 

Video, Further Resources & Summary

If you need more explanations on the R programming code of this article, you may want to have a look at the following video of my YouTube channel. I illustrate the R programming syntax of this page in the video instruction.

 

The YouTube video will be added soon.

 

Also, you may want to have a look at some of the related posts on https://statisticsglobe.com/. I have released numerous tutorials already:

 

In summary: In this R programming tutorial you have learned how to apply the equivalent to COUNTIF in Excel. Let me know in the comments section, if you have 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