r - R 中的第 53 周?

标签 r date dayofweek

我有形式为 yyyy-ww 的周日期数据哪里ww是两位数的周数。数据跨度2007-012010-30 .周计数惯例是 ISO 8601,正如您在此处看到的 on Wikipedia's "Week number" article ,偶尔达到一年 53 周。例如,2009 年有 53 周,请参阅 this ISO 8601 calendar 中的周数。 . (参见其他年份;根据维基百科文章,第 53 周相当罕见。)

基本上我想读取周日期,将其转换为 Date对象并将其保存到 data.frame 中的单独列中.作为测试,我重新转换了 Date反对 yyyy-ww格式 format([Date-object], format = "%Y-%W" ,这在 2009-53 抛出了一个错误.该周未能被 R 解释为日期.这很奇怪,因为其他没有第 53 周(在 ISO 8601 标准中)的年份转换得很好,例如 2007-53 ,而其他也没有第 53 周(在 ISO 8601 标准中)的年份也会失败,例如 2008-53
以下最小示例演示了该问题。

最小的例子:

dates <- c("2009-50", "2009-51", "2009-52", "2009-53", "2010-01", "2010-02")
as.Date(x = paste(dates, 1), format = "%Y-%W %w")
# [1] "2009-12-14" "2009-12-21" "2009-12-28" NA           "2010-01-04"
# [6] "2010-01-11"

other.dates <- c("2007-53", "2008-53", "2009-53", "2010-53")
as.Date(x = paste(other.dates, 1), format = "%Y-%W %w")
# [1] "2007-12-31" NA           NA           NA     

问题是,我如何获得 R接受 ISO 8601 格式的周数?

注意:这个问题总结了我几个小时以来一直在努力解决的问题。我搜索并找到了各种有用的帖子,例如 this ,但没有人解决问题。

最佳答案

包裹ISOweek管理 ISO 8601 样式周编号,与 Date 相互转换R 中的对象.见 ISOweek 更多。继续上面的示例日期,我们首先需要稍微修改格式。它们必须采用形式 yyyy-Www-w而不是 yyyy-ww ,即 2009-W53-1 .最后一位数字标识用于标识星期的星期几,在这种情况下是星期一。周数必须是两位数。

library(ISOweek)

dates <- c("2009-50", "2009-51", "2009-52", "2009-53", "2010-01", "2010-02")
other.dates <- c("2007-53", "2008-53", "2009-53", "2010-53")

dates <- sub("(\\d{4}-)(\\d{2})", "\\1W\\2-1", dates)
other.dates <- sub("(\\d{4}-)(\\d{2})", "\\1W\\2-1", other.dates)

## Check:
dates
# [1] "2009-W50-1" "2009-W51-1" "2009-W52-1" "2009-W53-1" "2010-W01-1"
# [6] "2010-W02-1"

(iso.date <- ISOweek2date(dates))             # deal correctly
# [1] "2009-12-07" "2009-12-14" "2009-12-21" "2009-12-28" "2010-01-04"
# [6] "2010-01-11"
(iso.other.date <- ISOweek2date(other.dates)) # also deals with this
# [1] "2007-12-31" "2008-12-29" "2009-12-28" "2011-01-03"

## Check that back-conversion works:
all(date2ISOweek(iso.date) == dates)
# [1] TRUE

## This does not work for the others, since the 53rd week of
## e.g. 2008 is back-converted to the first week of 2009, in
## line with the ISO 6801 standard.
date2ISOweek(iso.other.date) == other.dates
# [1] FALSE FALSE  TRUE FALSE

关于r - R 中的第 53 周?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14937837/

相关文章:

r - 如何循环数据帧中的变量列表,并为每个变量应用过滤器并获取加权频率表?

r - 导入 R 时的 SPSS 日期格式

R 计算有条件的连续天数

cron - 在 cron 表达式中使用月份和星期几

date - 不确定get(Calendar.DAY_OF_WEEK)返回什么

ios - 如何在 EKRecurrenceRule 中为星期几设置数组?

html - Shiny 中 selectInput 标签旁边的信息图标

r - 从年初的年周数获取一周第一天的日期

java - 在随机字符串内使用正则表达式匹配日期

Java 日期和时间戳