I am new to R, I have this massive data file with a list of user IDs. I want to replace those user IDs with a number i starting from 1 for each id. Is this possible?
Here's what I have:
Here's what I want:
I am new to R, I have this massive data file with a list of user IDs. I want to replace those user IDs with a number i starting from 1 for each id. Is this possible?
Here's what I have:
Here's what I want:
Try this solution using a as.factor
approach:
In df
you have your input data:
df<-data.frame(ID=c(7001,7001,8001,8002),A=c(1,2,3,4))
df
ID A
1 7001 1
2 7001 2
3 8001 3
4 8002 4
Replace ID
df$ID<-as.numeric(as.factor(df$ID))
df
ID A
1 1 1
2 1 2
3 2 3
4 3 4
We can use match
to get the index in the order of occurence of the unique ID's
dat$ID <- with(dat, match(ID, unique(ID)))
dat$ID
#[1] 1 1 2 3
Or use .GRP
from data.table
library(data.table)
setDT(dat)[, ID := .GRP, ID]
Based on the OP's description,
dat$ID <- cumsum(c(TRUE, diff(dat$E) < 0))