Here is an option
library(dplyr)
df1 %>%
group_by(ID, class) %>%
mutate(counter = row_number())
-output
# A tibble: 8 x 3
# Groups: ID, class [4]
# ID class counter
# <chr> <chr> <int>
#1 A z 1
#2 A z 2
#3 A c 1
#4 A c 2
#5 A z 3
#6 B z 1
#7 B c 1
#8 B c 2
Or with data.table
setDT(df1)[, counter := rowid(ID, class)]
data
df1 <- structure(list(ID = c("A", "A", "A", "A", "A", "B", "B", "B"),
class = c("z", "z", "c", "c", "z", "z", "c", "c"), counter = c(1L,
2L, 1L, 2L, 3L, 1L, 1L, 2L)), class = "data.frame", row.names = c(NA,
-8L))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…