[英]How to determine difference in days between two dates across two columns and two rows by group?
我希望通过两列和两行的组来确定天数差异。 基本上从结束日减去后续行中的后续开始日,并将差异记录为数据框中的新列,并在识别新组 (ID) 时重新开始。
Start_Date End_Date ID
2014-05-09 2015-05-08 01
2015-05-09 2016-05-08 01
2016-05-11 2017-05-10 01
2017-05-11 2018-05-10 01
2016-08-29 2017-08-28 02
2017-08-29 2018-08-28 02
结果应该类似于下表。
Start_Date End_Date ID Days_Difference
2014-05-09 2015-05-08 01 NA
2015-05-09 2016-05-08 01 01
2016-05-11 2017-05-10 01 03
2017-05-11 2018-05-10 01 01
2016-08-29 2017-08-28 02 NA
2017-08-29 2018-08-28 02 01
本质上,我想计算结束日期与其左对角线开始日期跨组 (ID) 的差异。 我真的很难过这个。 我不认为我的代码会有帮助。 任何使用 tidyverse、data.table 或 base R 的解决方案都将不胜感激!
分组后我们可能会得到 'Start_Date' 和 'End_Date' 的lead
数(下一个元素)之间的差异
library(dplyr)
df1 <- df1 %>%
mutate(across(ends_with("Date"), as.Date)) %>%
group_by(ID) %>%
mutate(Days_Difference = as.numeric(lag(lead(Start_Date) - End_Date))) %>%
ungroup
-输出
df1
# A tibble: 6 × 4
Start_Date End_Date ID Days_Difference
<date> <date> <int> <dbl>
1 2014-05-09 2015-05-08 1 NA
2 2015-05-09 2016-05-08 1 1
3 2016-05-11 2017-05-10 1 3
4 2017-05-11 2018-05-10 1 1
5 2016-08-29 2017-08-28 2 NA
6 2017-08-29 2018-08-28 2 1
或者与data.table
类似的逻辑
library(data.table)
setDT(df1)[, Days_Difference :=
as.numeric(shift(shift(as.IDate(Start_Date), type = "lead") -
as.IDate(End_Date))), ID]
-输出
> df1
Start_Date End_Date ID Days_Difference
<char> <char> <int> <num>
1: 2014-05-09 2015-05-08 1 NA
2: 2015-05-09 2016-05-08 1 1
3: 2016-05-11 2017-05-10 1 3
4: 2017-05-11 2018-05-10 1 1
5: 2016-08-29 2017-08-28 2 NA
6: 2017-08-29 2018-08-28 2 1
df1 <- structure(list(Start_Date = c("2014-05-09", "2015-05-09", "2016-05-11",
"2017-05-11", "2016-08-29", "2017-08-29"), End_Date = c("2015-05-08",
"2016-05-08", "2017-05-10", "2018-05-10", "2017-08-28", "2018-08-28"
), ID = c(1L, 1L, 1L, 1L, 2L, 2L)), class = "data.frame",
row.names = c(NA,
-6L))
另一个data.table
选项
setDT(df)[
,
c(lapply(.SD, as.IDate), .(ID = ID)),
.SDcols = patterns("Date$")
][
,
DayspDiff := Start_Date - shift(End_Date),
ID
][]
产量
Start_Date End_Date ID DayspDiff
1: 2014-05-09 2015-05-08 1 NA
2: 2015-05-09 2016-05-08 1 1
3: 2016-05-11 2017-05-10 1 3
4: 2017-05-11 2018-05-10 1 1
5: 2016-08-29 2017-08-28 2 NA
6: 2017-08-29 2018-08-28 2 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.