Often you may want to get the row numbers in a data frame in R that contain a certain value. Fortunately this is easy to do using the which() function.
This tutorial shows several examples of how to use this function in practice.
Example 1: Get Row Numbers that Match a Certain Value
Suppose we have the following data frame in R:
#create data frame df = data.frame(points=c(25, 12, 15, 14, 19), assists=c(5, 7, 7, 9, 12), team=c('Mavs', 'Mavs', 'Spurs', 'Celtics', 'Warriors')) #view data frame df points assists team 1 25 5 Mavs 2 12 7 Mavs 3 15 7 Spurs 4 14 9 Celtics 5 19 12 Warriors
We can use the following syntax to get the row numbers where ‘team’ is equal to Mavs:
#get row numbers where 'team' is equal to Mavs which(df$team == 'Mavs') [1] 1 2
We can see that the team name is equal to ‘Mavs’ at row numbers 0 and 1.
We can also use the %in% operator to get the row numbers where the team name is in a certain list of team names:
#get row numbers where 'team' is equal to Mavs or Spurs which(df$team %in% c('Mavs', 'Spurs')) [1] 1 2 3
We can see that the team name is equal to ‘Mavs’ or ‘Spurs’ at rows numbers 1, 2, and 3.
Example 2: Get Sum of Row Numbers
If we want to know the total number of rows where a column is equal to a certain value, we can use the following syntax:
#find total number of rows where team is equal to Mavs length(which(df$team == 'Mavs')) [1] 2
We can see that team is equal to ‘Mavs’ in a total of 2 rows.
Example 3: Return Data Frame with Certain Rows
And if we’d like to return a data frame where the rows in one column are equal to a certain value, we can use the following syntax:
#return data frame containing rows that have team equal to 'Mavs' df[which(df$team == 'Mavs'), ] points assists team 1 25 5 Mavs 2 12 7 Mavs
Notice that only the two rows where team is equal to ‘Mavs’ are returned.
Additional Resources
How to Sum Specific Columns in R
How to Loop Through Column Names in R