How to Perform a COUNTIF Function in R?
Last Updated :
24 Dec, 2021
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
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" ))
print ( sum (data$col3 == 'manoj' ))
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
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" ))
print ( sum (data$col1 >= 30))
print ( sum (data$col2 >= 10))
|
Output:
[1] 3
[1] 5
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...