Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an index (numeric ID) column to large data frame [duplicate]

Tags:

dataframe

r

I have a read large csv file into a data frame. Data in the csv file are from multiple web sites representing user information. For example here is the structure of the data frame.

user_id, number_of_logins, number_of_images, web 001, 34, 3, aa.com 002, 4, 4, aa.com 034, 3, 3, aa.com 001, 12, 4, bb.com 002, 1, 3, bb.com 034, 2, 2, cc.com 

as you can see once I bring the data into the data frame user_id is no longer a unique id and this causes all the analysis. I am trying to add another columns prior to user_id which is something like "generated_uid" and pretty much use the index of the data.frame to be filled by that column. What's the best way to accomplish this.

like image 617
add-semi-colons Avatar asked May 07 '14 13:05

add-semi-colons


People also ask

How do I add an index number to a Dataframe in R?

To Generate Row number to the dataframe in R we will be using seq.int() function. Seq.int() function along with nrow() is used to generate row number to the dataframe in R. We can also use row_number() function to generate row index.

How do I add row numbers to a column in R?

How to add unique row number to a dataframe in R using tidyverse. In order to add unique row number as one of the variables or columns to the dataset, we will use row_number() function with mutate() function from dplyr as shown below. Here we are assigning row number to a variable or column name “row_id”.


1 Answers

You can add a sequence of numbers very easily with

data$ID <- seq.int(nrow(data)) 

If you are already using library(tidyverse), you can use

data <- tibble::rowid_to_column(data, "ID") 
like image 178
MrFlick Avatar answered Sep 28 '22 13:09

MrFlick