Continuous weekly transition over the years
I am trying to calculate the offset of the week using as.Date
relative to any origin
or base date. For example:.
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"))
Gives: ad1w = 0
, ad2w = 16
. I would like ad1w
and ad2w
not to be 0 and 16, but a number with an offset to bd
. Is it possible? The origin can be any date. Thank you!
Clarify a little. Let them talk:
bd = as.Date("2013-12-25")
ad1 = as.Date("2015-01-07")
ad2 = as.Date("2015-01-06")
those. bd
- week in 2013, and ad1
and ad2
- week 1 in 2015. Both offsets must be 54 weeks without rounding.
source to share
is that enough?
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 as follows. Repeat code for each date to be the last date of the previous week and then useas.numeric(floor((recoded_ad1 - recoded_bd) /7))
source to share