R:错误地将 ISO-Week 转换为 Date

R: Wrong converting ISO-Week to Date

我有一年、一个 ISO 周和一个工作日(2015 年,第 7 周,工作日 1 == 2015-02-09),我想将其转换为日期。

所以我按以下方式进行:

date <- "2015:7:1"

as.Date(date, format="%Y:%V:%u")
[1] "2015-03-25"

如您所见,我弄错了日期(今天)。 当使用另一种格式字符串(%U 或 %W 而不是 %V)时,我得到“2015-02-16”结果——一周太晚了,因为 %U 和 %W 从 0 开始计算周数。

%V 我错过了什么?

问题是您可以使用 %V 进行输出,但不能进行输入。注意 ? strptime:

%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 并减去一周:

as.Date("2015:7:1", format = "%Y:%W:%u") - 7
[1] "2015-02-09"

然后注意如何在输出中允许 %V

strftime(as.Date("2015:7:1", format = "%Y:%W:%u") - 7, "%Y:%V:%u")
[1] "2015:07:1"

我想提醒一下。建议的计算方式并不总是有效,例如:

isoyear = c(2015, 2015)
isoweek = c(52, 53)
iyw=paste(isoyear,isoweek,1,sep=":")
as.Date(iyw, format = "%Y:%W:%u") - 7
[1] "2015-12-21" NA

但是如果我们检查“2015-12-31”的等周线,我们会得到以下信息:

isoweek("2015-12-28")
[1] 53

最好改用 ISOweek 包中的函数 ISOweek2date()。