4.5 C
London
Thursday, December 19, 2024
HomeStatistics TutorialRHow to Add an Index (numeric ID) Column to a Data Frame...

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

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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. 

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories