计算不同结束日期的工作年数

Calculate number of years worked with different end dates

考虑以下两个数据集。第一个数据集描述了一个 id 变量,该变量标识一个人以及他或她的失业救济金开始的日期。

第二个数据集显示了服务年限,这使得计算最长权利期限成为可能。更准确地说,每年表示一个虚拟变量,如果有人在特定年份(即如果有人工作)建立失业救济金权利,则它等于 1。如果不是这种情况,则此变量等于零。

df1<-data.frame( c("R005", "R006", "R007"), c(20120610, 20130115, 20141221))
colnames(df1)<-c("id", "start_UI")

df1$start_UI<-as.character(df1$start_UI)
df1$start_UI<-as.Date(df1$start_UI, "%Y%m%d")

df2<-data.frame( c("R005", "R006", "R007"), c(1,1,1), c(1,1,1), c(0,1,1), c(1,0,1), c(1,0,1) ) 

colnames(df2)<-c("id", "worked2010", "worked2011", "worked2012", "worked2013", "worked2014")

只是总结以上两个数据集的信息。我们看到 R005 这个人在 2010 年和 2011 年工作。在 2012 年,这个人申请了失业保险。此后,人 R005 在 2013 年和 2014 年再次工作(我们在数据集 df2 中看到此信息)。当他的失业期从 2012 年开始时,他的权利是基于他失业前 的工作经历。因此,工作经历等于 2。类似地,R006 和 R007 的工作经历分别等于 3 和 5(对于 R007,我们假设他在 2014 年工作,因为他在那一年的 12 月才申请失业救济金年。因此数字是 5 而不是 4)。

现在我的问题是如何有效地合并这两个数据集,以便我可以获得以下内容 table

df_final<- data.frame(c("R005", "R006", "R007"), c(20120610, 20130115, 20141221), c(2,3,5))
colnames(df_final)<-c("id", "start_UI", "employment_history")

    id start_UI employment_history
1 R005 20120610                  2
2 R006 20130115                  3
3 R007 20141221                  5

我尝试使用“汇总”,但在那种情况下,我还包括有人申请失业救济金的那一年之后的工作经历,这是我不想要的。有没有人有有效的方法来结合上述两个数据集的信息并计算失业历史?

感谢任何帮助。

基础 R

您应该将 Reduceaccumulate = T 一起使用。

df2$employment_history <- apply(df2[,-1], 1, function(x) sum(!Reduce(any, x==0, accumulate = TRUE)))
merge(df1, df2[c("id","employment_history")])

dplyr

或者使用内置的dplyr::cumany函数:

df2 %>% 
  pivot_longer(-id) %>% 
  group_by(id) %>% 
  summarise(employment_history = sum(value[!cumany(value == 0)])) %>% 
  left_join(df1, .)

输出

    id   start_UI employment_history
1 R005 2012-06-10                  2
2 R006 2013-01-15                  3
3 R007 2014-12-21                  5