Open In App

How to Perform a COUNTIF Function in R?

Last Updated : 24 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to perform COUNTIF function in R programming language.

This is used to count the value present in the dataframe. We have to use sum() function to get the count.

Syntax:

sum(dataframe$column_name == value, na.rm=TRUE)

where,

  • dataframe is the input dataframe
  • column_name is the column in the dataframe
  • na.rm is set to true to ignore NA values

Count Rows Equal to Some Value

To do that we simply equate the value and make it a count if the value is the given value.

Example: Count rows equal to some value

R




# create  dataframe with four columns
data = data.frame(col1=c(1, 34, 56, 32, 23),
                  col2=c(21, 34, 56, 32, 34),
                  col3=c("manoj", "sai", "sai", "manoj", "maghu"),
                  col4=c("java", "php", "jsp", "php", "html"))
 
 
# count manoj from col3
print(sum(data$col3 == 'manoj'))
 
# count 34 from col2
print(sum(data$col2 == 34))


Output:

[1] 2
[1] 2

Count Rows Greater or Equal to Some Value

In this, the condition is passed to the function simply. The count is incremented if the condition is satisfied.

Syntax:

sum(dataframe$column_name> value)

Example: Count rows greater or equal to some value

R




# create  dataframe with four columns
data = data.frame(col1=c(1, 34, 56, 32, 23),
                  col2=c(21, 34, 56, 32, 34),
                  col3=c("manoj", "sai", "sai", "manoj", "maghu"),
                  col4=c("java", "php", "jsp", "php", "html"))
 
 
# count value greater than or equal to 30 from col1
print(sum(data$col1 >= 30))
 
# count value greater than or equal to 10 from col2
print(sum(data$col2 >= 10))


Output:

[1] 3
[1] 5


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads