我有一个数据集如下
>df
id time cycle
1 0 1
1 5 NA
2 0 1
2 10 NA
2 20 NA
3 0 0
3 2 NA
3 5 NA
3 8 NA
3 15 NA
4 0 1
......
我希望所有这些都NA
自动累积到下一个ID,如下所示:
>df.new
id time cycle
1 0 1
1 5 2
2 0 1
2 10 2
2 20 3
3 0 1
3 2 2
3 5 3
3 8 4
3 15 5
4 0 1
......
应该有一种简单的方法可以在R中进行编码。请分享您的想法。谢谢!
df$cycle <- with(df, ave(cycle, id, FUN=seq_along))
df$cycle
#[1] 1 2 1 2 3 1 2 3 4 5 1
或者
sequence(tabulate(df$id)) #if IDs are in order
# [1] 1 2 1 2 3 1 2 3 4 5 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句