I have ID in my table I need to create a Count column based on ID.
ID Count
123 1
123 2
123 3
456 1
789 1
789 2
Kindly suggest me a code. Thanks in advance!
You can use ave
with seq_along
to get a row counter per ID
.
x$Count <- ave(integer(nrow(x)), x$ID, FUN=seq_along)
x
# ID Count
#1 123 1
#2 123 2
#3 123 3
#4 456 1
#5 789 1
#6 789 2
Data:
x <- structure(list(ID = c(123L, 123L, 123L, 456L, 789L, 789L), Count = c(1L,
2L, 3L, 1L, 1L, 2L)), row.names = c(NA, -6L), class = "data.frame")