我们可以用
match
具有
unique
lob
library(data.table)
dt[, priority := match(lob, unique(lob)), by = .(id, month)]
dt
# id lob month priority
# 1: 1 A 11 1
# 2: 1 A 11 1
# 3: 1 B 12 1
# 4: 1 B 1 1
# 5: 1 C 1 2
# 6: 2 A 11 1
# 7: 2 B 12 1
# 8: 2 C 12 2
# 9: 3 A 11 1
#10: 3 A 12 1
#11: 3 B 1 1
使用相同的逻辑
dplyr
版本
library(dplyr)
dt %>%
group_by(id, month) %>%
mutate(pr = match(lob, unique(lob)))
基本R版本使用
ave
dt$priority <- with(dt, ave(lob, id, month, FUN = function(x) match(x, unique(x))))