简体   繁体   English

R:错误地将ISO周转换为日期

[英]R: Wrong converting ISO-Week to Date

I've got a year, an ISO-Week and a weekday (year 2015, week 7, weekday 1 == 2015-02-09) and I'd like to convert it to the date. 我有一年,一个ISO周和一个工作日(2015年,第7周,工作日1 = 2015-02-09),我想将它转换为日期。

So I do it the following way: 所以我按照以下方式做到:

date <- "2015:7:1"

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

As you can see I get the wrong date (it's today). 你可以看到我得到了错误的日期(今天是这样)。 When using another format-string (%U or %W instead of %V) I get "2015-02-16" as a result -- one week too late because %U and %W count weeks from 0 on. 当使用另一个格式字符串(%U或%W而不是%V)时,我得到“2015-02-16” - 一周太晚了,因为%U和%W从0开始计算周数。

What am I missing with %V? %V我错过了什么?

The issue is that you can use %V for output, but not input. 问题是您可以使用%V输出,但不能输入。 Note in ? strptime 请注意? strptime ? strptime : ? 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.) %V:作为ISO 8601中定义的十进制数(01-53)的一年中的一周。如果包含1月1日的一周(从星期一开始)在新的一年中有四天或更多天,则将其视为第1周。否则,它是上一年的最后一周,下一周是第1周。 (接受但输入时忽略。)

So, that means you should probably use %W and subtract a week: 所以,这意味着您应该使用%W并减去一周:

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

And then note how %V is allowed on output: 然后注意输出允许%V

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

I'd like to caution. 我想提醒一下。 The suggested way of calculating doesn't always work as it should, for example: 建议的计算方法并不总是如此,例如:

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

but if we check the isoweek of "2015-12-31", we get the following: 但如果我们检查“2015-12-31”的isoweek,我们得到以下内容:

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

It's better to use the function ISOweek2date() from ISOweek package instead. 最好使用ISOweek包中的函数ISOweek2date()代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM