r语言 - 你如何计算以周为单位的间隔?



my x 是 2015 年的第 10 周,y 是 2015 年的第 20 周。

x<-as.Date("201510", "%Y%U")
y<-as.Date("201520", "%Y%U")

我想在周数上获得 x-y 之间的差异。 所以 x-y 应该是 -10。当我尝试使用以下代码时,我得到 0 或 0。

interval(x, y) / weeks(1)

这给了我 0

as.period(x- y, unit = "weeks")

这给了我0。

我在这里错过了什么?

你不需要lubridate。这是一个base R选项:

## you need to define a week day to be able to compute the time interval
x <- as.Date("2015107", "%Y%U%u") # by appending 7 (and %u) to the string, we are taking the last day of the week (i.e. sunday)
y <- as.Date("2015207", "%Y%U%u")
## time interval
difftime(x, y, units = "weeks") 
# Time difference of -10 weeks
as.numeric(difftime(x, y, units = "weeks"))
# [1] -10

如果您确实想要lubridate解决方案,请使用dweeks而不是weeks

x<-as.Date("2015107", "%Y%U%u") # using @ANG's edit to make the dates distinct
y<-as.Date("2015207", "%Y%U%u")
library(lubridate)
interval(y, x) / dweeks(1)
[1] -10

最新更新