gpt4 book ai didi

r - 年周在 R 中被错误解析

转载 作者:行者123 更新时间:2023-12-04 10:24:03 25 4
gpt4 key购买 nike

问题 :我面临的问题是 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 ,取决于您是要将星期日还是星期一视为一周的开始。

但是请注意,这些可能会导致 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 中被错误解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60706934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com