2.4 C
London
Friday, December 20, 2024
HomeRDescriptive Statistics in RHow to Perform a COUNTIF Function in R

How to Perform a COUNTIF Function in R

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

Often you may be interested in only counting the number of rows in an R data frame that meet some criteria. Fortunately this is easy to do using the following basic syntax:

sum(df$column == value, na.rm=TRUE)

The following examples show how to use this syntax in practice on the following data frame:

#create data frame
data #view data frame
data

    team points rebounds
1   Mavs     14        8
2   Mavs     NA        5
3  Spurs      8        5
4  Spurs     17        9
5 Lakers     22       12

Example 1: Count Rows Equal to Some Value

The following code shows how to count the number of rows where the team name is equal to “Mavs”:

sum(data$team == 'Mavs')

[1] 2

The following code shows how to count the number of rows where the team name is equal to “Mavs” or “Lakers”:

sum(data$team == 'Mavs' | data$team == 'Lakers')

[1] 3

The following code shows how to count the number of rows where the team name is not equal to “Lakers”:

sum(data$team != 'Lakers')

[1] 4

Example 2: Count Rows Greater or Equal to Some Value

The following code shows how to count the number of rows where points is greater than 10:

sum(data$points > 10, na.rm=TRUE)

[1] 3

The following code shows how to count the number of rows where rebounds is less than or equal to 9:

sum(data$rebounds TRUE)

[1] 4

Example 3: Count Rows Between Two Values

The following code shows how to count the number of rows where points is between 10 and 20:

sum(data$points > 10 & data$points TRUE)

[1] 2

The following code shows how to count the number of rows where rebounds is between 8 and 10:

sum(data$rebounds > 8 & data$rebounds TRUE)

[1] 1

Additional Resources

How to Count Observations by Group in R
How to Group & Summarize Data in R

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories