generate id for each group with repeated and missing observations

≯℡__Kan透↙ 提交于 2020-06-09 03:02:50

问题


I have a dataset with individuals observed over several weeks. Some individuals have no observations in some weeks, and some have several observations during the same week. I need to create a weekly ID(id_week in the code) that would be individual-specific. If an individual have two or more observations in one week, id_week should be the same for both observations. If an individual have no observations in a given week, the observation in a next week should be consuequent from the last observed point. This would result in a following data:

dt<-data.frame(individ=c(1,1,1,2,2,2,3,3,3,3),week=c(1,2,2,1,2,4,1,3,4,4),id_week=c(1,2,2,1,2,3,1,2,3,3))

I have tride dt[, id := .GRP, by = .(individ, week)] but it gives me just ID for weeks, not taken individuals into account. I also tried dplyr solution but it does not account for repeated observations within one week, assigning an ID to every line, which is not what I need.

dt%>%
group_by(individ)%>%
mutate(pp = row_number(week))

回答1:


An option using data.table:

setDT(dt)[, id_week := rleid(week), individ]



回答2:


Here are few alternatives :

1) Using dense_rank :

library(dplyr)
dt %>% group_by(individ) %>% mutate(id_week = dense_rank(week))

2) Using match and unique :

dt$id_week <- with(dt, ave(week, individ, FUN = function(x) match(x, unique(x))))

3) Converting to factor and then integer :

library(data.table)
setDT(dt)[, id_week := as.integer(factor(week)), individ]


来源:https://stackoverflow.com/questions/61865638/generate-id-for-each-group-with-repeated-and-missing-observations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!