3

我正在尝试使用as.Date相对于任何origin日期或基准日期来计算周偏移量。例如:

bd = as.Date("2013-12-29")
ad1 = as.Date("2014-01-01")
ad1w = as.numeric(strftime(ad1, format = "%W"))
ad2 = as.Date("2015-04-20")
ad2w = as.numeric(strftime(ad2, format = "%W"))

给出:ad1w = 0, ad2w = 16. 我希望ad1w并且ad2w不是 0 和 16,而是一个偏移量为 的数字bd。可能吗?来源可以是任何日期。谢谢!

澄清一点。比方说:

bd = as.Date("2013-12-25")
ad1 = as.Date("2015-01-07")
ad2 = as.Date("2015-01-06")

bd是 2013 年的第 51 周,并且两者ad1都是ad22015 年的第 1 周。两个偏移量都应该是 54 周,没有四舍五入。

4

1 回答 1

2

Would this suffice?

ad1w <- as.numeric(floor((ad1 - bd) /7))
ad2w <- as.numeric(floor((ad2 - bd) /7))

Update

using lubridate you can use:

library(lubridate)

ad1w <- as.numeric(floor((ad1-lubridate::wday(ad1) - (bd-lubridate::wday(bd))) /7))
ad2w <- as.numeric(floor((ad2-lubridate::wday(ad2) - (bd-lubridate::wday(bd))) /7))

The logic is the following. Re code each date to be the last date of the previous week, and then use the as.numeric(floor((recoded_ad1 - recoded_bd) /7))

于 2015-04-22T14:43:41.980 回答