How to Add an Index column to a Data Frame in R

by | Programming, R, Tips

The easiest way to add a sequence of numbers as an index column is to use the nrow() function, for example,

df$index <- 1:nrow(df)

This tutorial will explain how to add a numeric ID column to a data frame with code examples.


Add Index Column to Data Frame using $ Operator

Consider the following Data Frame:

df <- data.frame(subject=c('Physics', 'Chemistry', 'Biology', 'Mathematics'),
grades = c(80, 91, 74, 85))

df
subject grades
1     Physics     80
2   Chemistry     91
3     Biology     74
4 Mathematics     85

We can add a column containing numeric IDs using the nrow() function as follows:

require(dplyr)

# Add index column to Data Frame

df$index <- 1:nrow(df)

# Move index column to first column using relocate

df <- df %>% relocate(index, .before=subject)
df

Let’s run the code to see the result:

  index     subject grades
1     1     Physics     80
2     2   Chemistry     91
3     3     Biology     74
4     4 Mathematics     85

Add tibble::rowid_to_column

We can also use the tibble::rowid_to_column function from the tidyverse package as follows:

# Load tidyverse package 

library(tidyverse)

# Create Data Frame

df <- data.frame(subject=c('Physics', 'Chemistry', 'Biology', 'Mathematics'),
grades = c(80, 91, 74, 85))

# Add index column to Data Frame

df <- tibble::rowid_to_column(df,"index")

df

Let’s run the code to get the result:

 index     subject grades
1     1     Physics     80
2     2   Chemistry     91
3     3     Biology     74
4     4 Mathematics     85

Summary

Congratulations on reading to the end of this tutorial!

For further reading on R, go to the articles: 

Go to the online courses page on R to learn more about coding in R for data science and machine learning.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨