I am trying to find the right way in R to find duplicate values ββand add a value of 1 to each subsequent duplicate value, grouped by id. For instance:
data=data.table(id=c('1','1','1','1','1','2','2','2'),value=c(95,100,101,101,101,20,35,38)) data$new_value <- ifelse(data[,data$value] == lag(data$value,1), lag(data$value,1)+1 ,data$value) data$desired_value <- c(95,100,101,102,103,20,35,38)
Produces:
id value new_value desired_value 1: 1 95 NA 95 2: 1 100 100 100 3: 1 101 101 101 4: 1 101 102 102 5: 1 101 102 103 6: 2 20 20 20 7: 2 35 35 35 8: 2 38 38 38
I tried to do this with ifelse, but it doesnβt work recursively, so it only applies to the next line, not the next lines. Also, the lag function causes me to lose the first value in value .
I saw character variable examples with make.names or make.unique , but couldn't find a solution for a duplicate numeric value.
Reference Information. I do a survival analysis, and I find that the stopping time is the same with my data, so I need to make it unique by adding 1 (stopping time in seconds).