我想在数据框的每个组/子集中生成一个ID号,其中每个组由两个或多个字段定义。在此测试数据集中,我想使用“ personid”和“ date”作为类别:
personid date measurement
1 x 23
1 x 32
2 y 21
3 x 23
3 z 23
3 y 23
我希望为id列添加一个值,该值分别是两个列“ personid”和“ date”的每个唯一组合的值,始终以1开头。这是我想要的输出:
personid date measurement id
1 x 23 1
1 x 32 1
2 y 21 1
3 x 23 1
3 z 23 2
3 y 23 3
这与3年的版本类似,为数据框的每个组中的行创建一个序列号(计数器),但是经过多次尝试,我无法扩展其2+字段类别定义的逻辑。谢谢!
与@Procrastinatus Maximus的想法相同rleid
,这是dplyr
它的一个版本:
library(dplyr)
df %>%
arrange(personid, date) %>%
group_by(personid) %>%
mutate(id = cumsum(date != lag(date, default = first(date))) + 1)
# +1 converts the zero based id to one based id here
# Source: local data frame [6 x 4]
# Groups: personid [3]
#
# personid date measurement id
# <int> <fctr> <int> <dbl>
# 1 1 x 23 1
# 2 1 x 32 1
# 3 2 y 21 1
# 4 3 x 23 1
# 5 3 y 23 2
# 6 3 z 23 3
为了rleid
或cumsum
在这里工作,我们必须由数据帧进行排序personid
,然后date
,因为这两种方法只在乎相邻值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句