Home » How to Add an Index (numeric ID) Column to a Data Frame in R

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

by Erma Khan

Suppose you have the following data frame:

data 
                   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 

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 #add index column to data frame
data 

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

Related Posts