什么使 lubridate 中的负数?
What makes negative number in lubridate?
(today() %--% ymd("2000-01-01")) %/% years(1)
# -18
(ymd("2000-01-01") %--% today()) %/% years(1)
# 18
我认为 2018 - 2000 = 18,而不是 -18
不知我是不是完全看不懂%--%
必须使用 library(lubridate)
在他们的环境中获得这个中缀函数。
因此,如果您查看 ?%--%
的文档,它说:
interval() creates an Interval object with the specified start and end
dates. If the start date occurs before the end date, the interval will
be positive. Otherwise, it will be negative.
interval(today(), ymd("2000-01-01"))/years(1)
#start date occurs after the end date, this should be negative
打印interval(today(), ymd("2000-01-01"))
只会显示间隔范围而不显示符号,如果你使用as.numeric或使用年(1)除法,它会显示符号,因此会出现这种情况:
> interval(today(), ymd("2000-01-01"))/years(1)
[1] -18.57377
根据文档,中缀函数 %--%
会发生类似的行为:
%--% Creates an interval that covers the range spanned by two dates.
它的工作原理类似于您的间隔函数,因为它调用间隔函数。您可以通过打印 body(`%--%`)
来检查这一点,现在,如果您在结束日期之前的中缀函数开始日期中提供第一个参数,则给定输出为正,否则为负。
记住函数说的是开始日期和结束日期,这意味着开始应该更小,结束应该是更大的日期值以获得肯定的结果。在您的情况下,today() 是在开始日期之前出现的结束值,因此它是负数。
我希望这能澄清你的疑问。
(today() %--% ymd("2000-01-01")) %/% years(1)
# -18
(ymd("2000-01-01") %--% today()) %/% years(1)
# 18
我认为 2018 - 2000 = 18,而不是 -18
不知我是不是完全看不懂%--%
必须使用 library(lubridate)
在他们的环境中获得这个中缀函数。
因此,如果您查看 ?%--%
的文档,它说:
interval() creates an Interval object with the specified start and end dates. If the start date occurs before the end date, the interval will be positive. Otherwise, it will be negative.
interval(today(), ymd("2000-01-01"))/years(1)
#start date occurs after the end date, this should be negative
打印interval(today(), ymd("2000-01-01"))
只会显示间隔范围而不显示符号,如果你使用as.numeric或使用年(1)除法,它会显示符号,因此会出现这种情况:
> interval(today(), ymd("2000-01-01"))/years(1)
[1] -18.57377
根据文档,中缀函数 %--%
会发生类似的行为:
%--% Creates an interval that covers the range spanned by two dates.
它的工作原理类似于您的间隔函数,因为它调用间隔函数。您可以通过打印 body(`%--%`)
来检查这一点,现在,如果您在结束日期之前的中缀函数开始日期中提供第一个参数,则给定输出为正,否则为负。
记住函数说的是开始日期和结束日期,这意味着开始应该更小,结束应该是更大的日期值以获得肯定的结果。在您的情况下,today() 是在开始日期之前出现的结束值,因此它是负数。
我希望这能澄清你的疑问。