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 #  "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
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 #  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 #  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.