我的输入是数字格式,表示年份和星期数,我需要从一个输入到另一个输入创建一个序列。
输入示例:
input.from <- 202144
input.to <- 202208
期望输出为:
c(202144:202152, 202201:202208)
在我看来,这有点复杂,因为有这些限制:
- 53周的年份:我尝试了
lubridate::isoweek()
,%W
或%v
格式,… - 总是保持两位数的星期:我试过
"%02d"
,…
我还尝试将我的输入转换为日期,…无论如何,许多尝试都没有成功创建我的函数。
谢谢你的帮助!
,以防它会有用的人一天,最后我写的函数,这方面ISO 8601:
library(ISOweek)
foo <- function(pdeb, pfin) {
from <- ISOweek::ISOweek2date(paste0(substr(pdeb, 1, 4), "-W", substr(pdeb, 5, 6), "-1"))
to <- ISOweek::ISOweek2date(paste0(substr(pfin, 1, 4), "-W", substr(pfin, 5, 6), "-1"))
res <- seq.Date(from, to, by = "week")
return(format(res, format = "%G%V"))
}
foo(201950, 202205)
步骤#1:将输入转换为字符:YYYY-"W"WW-1
步骤#2:捕获ISOweek
步骤#3:按周排序
步骤#4:将序列返回为格式"%G%V",仍然尊重ISO 8601和yyyywww
我选
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"
如果你真的想让它们保持%Y%W
格式,那么
format(out, format = "%Y%W")
# [1] "202144" "202145" "202146" "202147" "202148" "202149" "202150" "202151" "202152" "202201" "202202" "202203" "202204"
# [14] "202205" "202206" "202207" "202208"
(这个答案在很大程度上由Transform year/week to date对象提供)
我们可以做一些数学运算。
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