How to add an Index (numeric ID) Column to a Data Frame in R

In R, you can add an index column to a data frame using the row.names() function. This function takes the row numbers of the data frame as an argument and assigns them as the new index column. You can then use the index column to reference individual rows in the data frame. Additionally, you can set the start and increment values for the index column to customize the values.


Suppose you have the following data frame:

data <- data.frame(team = c('Spurs', 'Lakers', 'Pistons', 'Mavs'),
                   avg_points = c(102, 104, 96, 97))
data

#     team avg_points
#1   Spurs        102
#2  Lakers        104
#3 Pistons         96
#4    Mavs         97

In order to add an index column to give each row in this data frame a unique numeric ID, you can use the following code:

#add index column to data frame
data$index <- 1:nrow(data)
data

#     team avg_points index
#1   Spurs        102     1
#2  Lakers        104     2
#3 Pistons         96     3
#4    Mavs         97     4

Another way to add a unique ID to each row in the data frame is by using the tibble::rowid_to_column function from the tidyverse package:

#load tidyverse package
library(tidyverse)

#create data frame
data <- data.frame(team = c('Spurs', 'Lakers', 'Pistons', 'Mavs'),
                   avg_points = c(102, 104, 96, 97))

#add index column to data frame
data <- tibble::rowid_to_column(data, "index")
data

#  index team avg_points
#1  1   Spurs        102
#2  2  Lakers        104
#3  3 Pistons         96
#4  4    Mavs         97

Notice that both techniques produce the same result: a new column that gives each row in the data frame a unique ID. 

x