如何解决R中data.frame中的日期重叠
我正在尝试根据日期重叠在我的数据框中创建一个新变量。
我的data
看起来像这样
People Company Start End
1 Person1 CompanyA 2017-04-27 2019-12-31
2 Person2 CompanyB 2017-04-27 2019-08-30
3 Person3 CompanyA 2013-04-27 2019-12-31
4 Person4 CompanyB 2017-04-27 2019-12-31
5 Person5 CompanyC 2016-05-13 2019-12-31
我想通过以下 dates
2016-12-31
2017-12-31
2018-12-31
2019-12-31
...
我正在使用 %overlaps%
库中的 DescTools
。如果我只检查 data
c(data$Start[1],data$End[1]) %overlaps% dates[1]
如我所料,它返回 TRUE
(或在其他情况下为 FALSE
)。但我想知道每一行的这一点,并将其保存在我的变量 data$y2017
、data$y2018
、data$y2019
等中。但是我遇到了这个问题。
因为如果我只是尝试在每一行上执行此操作,则它不起作用并且只为每一行返回 NA
。例如,如果我尝试查看 2016-12-31
中有谁:
data$y2016 <- c(data$Start,data$End) %overlaps% dates[1]
我该怎么做?
解决方法
这是一个 data.table
方法
此解决方案的核心是 data.table::foverlaps()
函数,用于检查 DT.dates
数据中的 Start-End 区间是否在 DT
中的 Start-End 区间内。
library(data.table)
# Sample data
DT <- fread(" People Company Start End
Person1 CompanyA 2017-04-27 2019-12-31
Person2 CompanyB 2017-04-27 2019-08-30
Person3 CompanyA 2013-04-27 2019-12-31
Person4 CompanyB 2017-04-27 2019-12-31
Person5 CompanyC 2016-05-13 2019-12-31")
DT[,Start := as.Date(Start)]
DT[,End := as.Date(End)]
DT.dates <- data.table( Start = as.Date(c("2016-12-31","2017-12-31","2018-12-31","2019-12-31")),End = as.Date(c("2016-12-31","2019-12-31")))
# Set keys
setkey(DT,Start,End)
setkey(DT.dates,End)
# Perform overlapjoin and cast to wide
dcast(foverlaps(DT.dates,DT),People + Company + Start + End ~ i.Start,value.var = "i.Start",fun.aggregate = length)
# People Company Start End 2016-12-31 2017-12-31 2018-12-31 2019-12-31
# 1: Person1 CompanyA 2017-04-27 2019-12-31 0 1 1 1
# 2: Person2 CompanyB 2017-04-27 2019-08-30 0 1 1 0
# 3: Person3 CompanyA 2013-04-27 2019-12-31 1 1 1 1
# 4: Person4 CompanyB 2017-04-27 2019-12-31 0 1 1 1
# 5: Person5 CompanyC 2016-05-13 2019-12-31 1 1 1 1
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。