标记持续观察并创建入学率
我有一些大型注册数据集,我正在尝试创建两件事:
- 我想标记每个不间断的每月观察(
final_df1
), - 我想创建一个不间断跨度的数据集(< 我觉得{lubritation}和{data.table}之间
例如:
library(tidyverse)
library(lubridate)
library(magrittr)
df<-tibble(id=c(rep("X",10),rep("Y",20)),
date=c(ymd("20120101")%m+%months(c(1:5,7:11)),ymd("20120401")%m+%months(c(1:10,12:17,19:22))))
final_df1 <- df %>% mutate(cont_enroll=c(rep(1,5),rep(0,5),rep(1,10),rep(0,10)))
final_df2 <- tibble(id=c(rep("X",2),rep("Y",3)),
span_start=c(ymd("20120101")%m+%months(1),
ymd("20120101")%m+%months(7),
ymd("20120401")%m+%months(1),
ymd("20120101")%m+%months(12),
ymd("20120101")%m+%months(19)),
span_end=c(ymd("20120101")%m+%months(5),
ymd("20120101")%m+%months(11),
ymd("20120101")%m+%months(10),
ymd("20120101")%m+%months(17),
ymd("20120101")%m+%months(22))
)
必须有一种简单的方法来执行此操作,但我觉得我正在绘制空白。有技巧吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由“ ID”分组,创建一个
Interval
,其先前的“日期”(lag
)和当前的“日期”,除以月份,检查它是否小于2,然后采取累积最小值(
first 和Cummin
)。创建“ find_df_new'之后,然后我们按'id'和'cont_enroll'列的运行长度ID进行分组,总结
>最后
“日期”的值分别创建“ span_start”和“ span_end”Grouped by 'id', create an
interval
with the previous value of 'date' (lag
) and the current 'date', divide by themonths
, check if it is less than 2, and take the cumulative minimum (cummin
). After creating the 'find_df_new', then we group by 'id' and the run-length-id of 'cont_enroll' column, andsummarise
with thefirst
andlast
value of 'date' to create the 'span_start' and 'span_end' respectively我认为您可以用 ivs 软件包来解决这个问题。您的日期似乎确实代表了1个月的间隔,而IVS软件包专门用于处理此类数据。
我们可以用
final_df2
用iv_groups()
来返回合并所有重叠间隔后保留的非重叠间隔。然后,每个组的第一行
final_df2
表示第一个连续间隔,因此您只需要检查每个范围是否在该间隔内,即可确定它是否是不间断设置的一部分以获取final_df1
。请注意,我的
final_df2
看起来与您的有可能在编码方式上有错误吗?由
I think you can solve this nicely with the ivs package. Your dates seem to really represent 1 month intervals, and the ivs package is dedicated to working with data of this type.
We can compute
final_df2
withiv_groups()
, which returns the non-overlapping intervals that remain after merging all overlapping intervals.Then the first row of
final_df2
per group represents the first continuous interval, so you just need to check if each range is within that interval or not to decide if it is part of the uninterrupted set to getfinal_df1
.Note that my
final_df2
looks different from yours, is it possible that you have an error in how you coded it?Created on 2022-05-13 by the reprex package (v2.0.1)