问题:我面临 R 将日期(2019 年 12 月 30 日)错误解析为年周的问题(输出:2019 W01)。我不知道为什么会发生这种情况。有什么建议可以改变/替代编码方式吗?
format(lubridate::ymd("2019-12-30"), "%Y W%V")
# Output
# 2019 W01
# Desired Output:
# 2019 W52
最佳答案
%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
,具体取决于您是否要将星期日或星期一视为一周的开始。
但请注意,这些可能会导致 00
和 53
之间的值,这是将一周的开始固定为特定工作日(周日或周一)的结果)。这样做意味着在年初和年底实际上可能会有不完整的一周。
如果您希望根据从一年的第一天开始的第 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/