How can I retrieve row numbers in R?

In R, the row numbers of a data frame or matrix can be retrieved by using the function “rownames()”. This function returns a vector containing the row names of the specified data structure, which can then be used to identify the row numbers. Additionally, the function “rownames_to_column()” can be used to add a column to the data frame that contains the row numbers. This allows for easy access and manipulation of the row numbers in R.

Retrieve Row Numbers in R (With Examples)


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 Spurswhich(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 Mavslength(which(df$team == 'Mavs'))

[1] 2

We can see that team is equal to ‘Mavs’ in a total of 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

x