R: How to Count Values in Column with Condition


You can use the following methods to count the number of values in a column of a data frame in R with a specific condition:

Method 1: Count Values in One Column with Condition

nrow(df[df$column1 == 'value1', ])

Method 2: Count Values in Multiple Columns with Conditions

nrow(df[df$column1 == 'value1' & df$column2 == 'value2', ]) 

The following examples show how to use each method in practice with the following data frame in R:

#create data frame
df <- data.frame(team=c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'),
                 position=c('G', 'G', 'F', 'F', 'G', 'G', 'F', 'F'),
                 points=c(10, 12, 3, 14, 22, 15, 17, 17))

#view data frame
df

  team position points
1    A        G     10
2    A        G     12
3    A        F      3
4    A        F     14
5    B        G     22
6    B        G     15
7    B        F     17
8    B        F     17

Example 1: Count Values in One Column with Condition

The following code shows how to count the number of values in the team column where the value is equal to ‘A‘:

#count number of rows where team is equal to 'B'
nrow(df[df$team == 'B', ])

[1] 4

We can see that there are 4 values in the team column where the value is equal to ‘B.’

Example 2: Count Values in Multiple Columns with Conditions

The following code shows how to count the number of rows in the data frame where the team column is equal to ‘B’ and the position column is equal to ‘F’:

#count number of rows where team is equal to 'B' and position is equal to 'F'
nrow(df[df$team == 'B' & df$position == 'F', ])

[1] 2

We can see there are 2 rows in the data frame that meet both of these conditions.

We can use similar syntax to count the number of rows that meet any number of conditions we’d like.

For example, the following code shows how to count the number of rows that meet three conditions:

  • team is equal to ‘B’
  • position is equal to ‘G’
  • points is greater than 20
#count rows where team is 'B' and position is 'G' and points > 20
nrow(df[df$team == 'B' & df$position == 'G' & df$points > 20, ])

[1] 1

We can see that only 1 row in the data frame meets all three of these conditions.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Count Number of Rows in R
How to Select Unique Rows in a Data Frame in R

Leave a Reply

Your email address will not be published.