Count Occurrences of Value in Data Frame in R (2 Examples)

 

This tutorial explains how to count the number of times a certain entry occurrs in a data frame in the R programming language.

The post looks as follows:

Let’s take a look at some R codes in action.

 

Creating Example Data

I’ll use the following data as a basis for this R programming language tutorial:

data <- data.frame(x1 = letters[1:5],    # Create example data frame
                   x2 = c("a", "b", "b", "a", "b"),
                   x3 = "b")
data                                     # Print example data frame

 

table 1 data frame count occurrences value data frame r

 

Table 1 shows the structure of our exemplifying data: It is made up of five data points and three character columns.

 

Example 1: Count Certain Value in One Column of Data Frame

In this example, I’ll demonstrate how to get the number of times a particular entry appears in a specific variable of a data frame.

For this task, we can apply the sum function to a logical condition as shown below:

sum(data$x2 == "b")                      # Count in one column
# [1] 3

The RStudio console has returned the value 3 after executing the previous R code, i.e. the character “b” occurs three times in the column x2.

 

Example 2: Count Certain Value in Entire Data Frame

This example explains how to count a certain value in all columns of a data frame in R.

Once again, we can use the sum function to accomplish this. However, this time we are not specifying a certain column (as we did in Example 1):

sum(data == "b")                         # Count in all columns
# [1] 9

As you can see, the character “b” is contained nine times in our example data set.

 

Video, Further Resources & Summary

If you need more information on the R programming code of this tutorial, you might want to watch the following video that I have published on my YouTube channel. In the video, I’m explaining the examples of this article.

 

The YouTube video will be added soon.

 

Besides that, you may want to read some of the related RStudio articles on my website. Please find a selection of related tutorials about related topics such as numeric values, data inspection, character strings, and vectors below:

 

To summarize: In this article, I have explained how to count a certain entry occurs in a data frame in the R programming language. Don’t hesitate to let me know in the comments section below, in case you have additional 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.


4 Comments. Leave new

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