在 R 中使用 ISO-8601 格式创建年和周向量

Create a vector of years and weeks with ISO-8601 format in R

我想创建一个从一个日期到另一个日期的矢量,显示为 YYYYWW,按周递增。重要的是星期以 ISO-8601 标准格式显示,这里有一个 link 以供参考 ISO-8601:https://www.epochconverter.com/weeks/2021

据我所知,以这种格式生成周的最巧妙方法是使用 lubridates isoyear 和 isoweek。例如:

from_date <- paste0(lubridate::isoyear("2020-01-01"),lubridate::isoweek("2021-01-01"))

> from_date
> "202053"

to_date <- paste0(lubridate::isoyear(Sys.Date()),lubridate::isoweek(Sys.Date()))
    
> to_date    
> "20222"

如何在 from_date 和 to_date 之间创建一个以一周为增量并保持 ISO-8601 标准的数组?

我试过

YearWeek <- seq(from_date, to_date, by = "weeks")

但在这种情况下 seq 的日期为 类,这迫使我脱离了 ISO-8601 标准。 作为参考,我希望我的最终结果如下所示:

# Vector of YearWeek from 2021-01-01 to todays date incrmented by week

> YearWeek
>  [1] 202053 202101 202102 202103 202104 202105 202106 202107 202108 202109 202110 202111 202112 202113 202114
  [16] 202115 202116 202117 202118 202119 202120 202121 202122 202123 202124 202125 202126 202127 202128 202129
  [31] 202130 202131 202132 202133 202134 202135 202136 202137 202138 202139 202140 202141 202142 202143 202144
  [46] 202145 202146 202147 202148 202149 202150 202151 202152 202201

请在下面找到您正在寻找的一种可能的解决方案:

Reprex

  • 代码
library(lubridate)

# Data
vec_date <- seq(date("2020-01-01"), date("2022-01-12"), by = "weeks")

# Convert data into isodate and isoweek
vec_date_iso <- paste0(lubridate::isoyear(vec_date),lubridate::isoweek(vec_date))
  • 输出
vec_date_iso 
#>   [1] "20201"  "20202"  "20203"  "20204"  "20205"  "20206"  "20207"  "20208" 
#>   [9] "20209"  "202010" "202011" "202012" "202013" "202014" "202015" "202016"
#>  [17] "202017" "202018" "202019" "202020" "202021" "202022" "202023" "202024"
#>  [25] "202025" "202026" "202027" "202028" "202029" "202030" "202031" "202032"
#>  [33] "202033" "202034" "202035" "202036" "202037" "202038" "202039" "202040"
#>  [41] "202041" "202042" "202043" "202044" "202045" "202046" "202047" "202048"
#>  [49] "202049" "202050" "202051" "202052" "202053" "20211"  "20212"  "20213" 
#>  [57] "20214"  "20215"  "20216"  "20217"  "20218"  "20219"  "202110" "202111"
#>  [65] "202112" "202113" "202114" "202115" "202116" "202117" "202118" "202119"
#>  [73] "202120" "202121" "202122" "202123" "202124" "202125" "202126" "202127"
#>  [81] "202128" "202129" "202130" "202131" "202132" "202133" "202134" "202135"
#>  [89] "202136" "202137" "202138" "202139" "202140" "202141" "202142" "202143"
#>  [97] "202144" "202145" "202146" "202147" "202148" "202149" "202150" "202151"
#> [105] "202152" "20221"  "20222"

reprex package (v2.0.1)

创建于 2022-01-12