r - R 中的 Yearweek 解析错误

标签 r date

问题:我面临 R 将日期(2019 年 12 月 30 日)错误解析为年周的问题(输出:2019 W01)。我不知道为什么会发生这种情况。有什么建议可以改变/替代编码方式吗?

format(lubridate::ymd("2019-12-30"), "%Y W%V")
# Output
# 2019 W01

# Desired Output:
# 2019 W52

最佳答案

来自strptime documentation :

%U
    Week of the year as decimal number (00–53) using Sunday as the first day 1 of the 
    week (and typically with the first Sunday of the year as day 1 of week 1). The US
    convention.

%V
    Week of the year as decimal number (01–53) as defined in ISO 8601. If the week
    (starting on Monday) containing 1 January has four or more days in the new year,
    then it is considered week 1. Otherwise, it is the last week of the previous year, 
    and the next week is week 1. (Accepted but ignored on input.)

%W
    Week of the year as decimal number (00–53) using Monday as the first day of week
    (and typically with the first Monday of the year as day 1 of week 1). The UK 
    convention.

听起来您可能需要 %U%W,具体取决于您是否要将星期日或星期一视为一周的开始。

但请注意,这些可能会导致 0053 之间的值,这是将一周的开始固定为特定工作日(周日或周一)的结果)。这样做意味着在年初和年底实际上可能会有不完整的一周。

如果您希望根据从一年的第一天开始的第 1 周进行计数,可以使用函数 lubridate::week

例如:

library(lubridate)
year_week <- function(date) paste0(year(date), ' W', week(date))

year_week(ymd("2019-01-01"))
# Result: "2019 W1"

year_week(ymd("2019-12-30"))
# Result: "2019 W52"

关于r - R 中的 Yearweek 解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60706934/

相关文章:

r - 删除前几行并将标题名称更改为行值

Javascript:将字符串转换为完整的月份到日期对象

带有插入日期的 php/Mysql 查询失败

sql - 如何获取星期六的日期(或任何其他工作日的日期)- SQL Server

iPhone 核心数据 : How to group fetched results by day?

r - 在 R 中绘制重叠位置

r - 如何在 alpine 中安装 R 3.4.4

java - 将日期转换为SimpleDateFormat时引发不可解析的日期错误

删除或隐藏 R ggplot2/factoextra 图上的零线

r - 将 PDF 中未嵌入的字体替换为同系列其他字体的最佳方法是什么?