将不同符号的持续时间与 lubridate 进行比较
我正在使用带有日期的数据集:
a <- structure(list(ID1 = c(1, 2, 3), ID2 = c(4,
5, 6), dob.x = structure(c(-9954, -8960, -1219), class = "Date"),
dob.y = structure(c(-1057, -1157, -9752), class = "Date")), row.names = c(NA,
3L), class = "data.frame")
ID1 ID2 dob.x dob.y
1 1 4 1942-10-01 1967-02-09
2 2 5 1945-06-21 1966-11-01
3 3 6 1966-08-31 1943-04-21
我需要获取这两个日期之间的差异,然后使用 filter()
函数将其与固定的年数进行比较,例如
a %>%
filter(diff > 21)
我尝试使用lubridate 来完成此任务,但如果我计算日期之间的差异,我无法比较它们,因为它们有不同的符号:
> a %>% mutate(diff = as.duration(interval(dob.x, dob.y)))
ID1 ID2 dob.x dob.y diff
1 1 4 1942-10-01 1967-02-09 768700800s (~24.36 years)
2 2 5 1945-06-21 1966-11-01 674179200s (~21.36 years)
3 3 6 1966-08-31 1943-04-21 -737251200s (~-23.36 years)
> a %>% mutate(diff = as.duration(interval(dob.x, dob.y))) %>% filter(diff > years(22))
ID1 ID2 dob.x dob.y diff
1 1 4 1942-10-01 1967-02-09 768700800s (~24.36 years)
当我有负值时,如何保留间隔超过例如 22 年的日期对?
I am working with a dataset with dates:
a <- structure(list(ID1 = c(1, 2, 3), ID2 = c(4,
5, 6), dob.x = structure(c(-9954, -8960, -1219), class = "Date"),
dob.y = structure(c(-1057, -1157, -9752), class = "Date")), row.names = c(NA,
3L), class = "data.frame")
ID1 ID2 dob.x dob.y
1 1 4 1942-10-01 1967-02-09
2 2 5 1945-06-21 1966-11-01
3 3 6 1966-08-31 1943-04-21
I need to get the difference between those two dates, and then use a filter()
function to compare it with a fixed number of years, e.g.
a %>%
filter(diff > 21)
I tried to use lubridate for this task, but if I compute the difference between dates I cannot compare them, as they have different signs:
> a %>% mutate(diff = as.duration(interval(dob.x, dob.y)))
ID1 ID2 dob.x dob.y diff
1 1 4 1942-10-01 1967-02-09 768700800s (~24.36 years)
2 2 5 1945-06-21 1966-11-01 674179200s (~21.36 years)
3 3 6 1966-08-31 1943-04-21 -737251200s (~-23.36 years)
> a %>% mutate(diff = as.duration(interval(dob.x, dob.y))) %>% filter(diff > years(22))
ID1 ID2 dob.x dob.y diff
1 1 4 1942-10-01 1967-02-09 768700800s (~24.36 years)
How do I keep pairs of dates with intervals over e.g. 22 years when I have negative values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
abs()
适用于持续时间,因为它们存储为带有符号的向量元素(以秒为单位):abs()
works on durations, as they're stored as elements of a vector with a sign (in seconds):