基于带日期的列的具有重复元素的序列列

Column of sequence with repeated elements based on column with dates

考虑按日期列排序的数据框:

df=data.frame(event=1:12,
              subject=rep("M325",12),
              date=c(rep("2017-11-01",4),rep("2017-11-14",8)))

我想要的是创建第四列,其中包含从 1 到下一个唯一日期的序列,序列中的每个元素每隔 i-th 日期重复一次。例如:

   event subject       date num
1      1    M325 2017-11-01   1
2      2    M325 2017-11-01   1
3      3    M325 2017-11-01   1
4      4    M325 2017-11-01   1
5      5    M325 2017-11-14   2
6      6    M325 2017-11-14   2
7      7    M325 2017-11-14   2
8      8    M325 2017-11-14   2
9      9    M325 2017-11-14   2
10    10    M325 2017-11-14   2
11    11    M325 2017-11-14   2
12    12    M325 2017-11-14   2

对于在 n 日期获得此结果的任何建议将不胜感激。

尽管@akrun 回答

df$num <-cumsum(!duplicated(df$date))

或使用data.table:

setDT(df)[, num := rleid(date)]

比较快,居然可以解决我的问题。