From my inputs, which is numeric format and represent the year and the week number, I need to create a sequence, from one input to the other.
Inputs example :
input.from <- 202144
input.to <- 202208
Desired output would be :
c(202144:202152, 202201:202208)
According to me, it is a little more complex, because of these constraints :
- Years with 53 weeks : I tried
lubridate::isoweek()
, the%W
or%v
format, ... - Always keep two digits for the week : I tried
"d"
, ...
I also tried to convert my input to date, ... Anyway, many attemps without success to create my function.
Thanks for your help !
CodePudding user response:
I'd go with
x <- c("202144", "202208")
out <- do.call(seq, c(as.list(as.Date(paste0(x, "1"), format="%Y%U%u")), by = "week"))
out
# [1] "2021-11-01" "2021-11-08" "2021-11-15" "2021-11-22" "2021-11-29" "2021-12-06" "2021-12-13" "2021-12-20" "2021-12-27"
# [10] "2022-01-03" "2022-01-10" "2022-01-17" "2022-01-24" "2022-01-31" "2022-02-07" "2022-02-14" "2022-02-21"
If you really want to keep them in the %Y%W
format, then
format(out, format = "%Y%W")
# [1] "202144" "202145" "202146" "202147" "202148" "202149" "202150" "202151" "202152" "202201" "202202" "202203" "202204"
# [14] "202205" "202206" "202207" "202208"
(This answer heavily informed by Transform year/week to date object)
CodePudding user response:
We could do some mathematics.
f <- function(from, to) {
r <- from:to
r[r %% 100 > 0 & r %% 100 < 53]
}
input.from <- 202144; input.to <- 202208
f(input.from, input.to)
# [1] 202144 202145 202146 202147 202148 202149 202150 202151 202152
# [10] 202201 202202 202203 202204 202205 202206 202207 202208