我尝试使用来自lubridate的parse_date_time将格式为WeekYear的字符串转换为日期。但我总是得到相同的日期作为回报。
library(lubridate)
> isoweek(parse_date_time("092015", orders = "WY"))
[1] 53
不应该像:?
> month(parse_date_time("092015", orders = "mY"))
[1] 9
当我将一周的第一天添加到日历周时,情况并没有好转:
> test <- c("2013-01-01","2013-02-02","2014-12-12")
> parse_date_time(paste(isoyear(test),isoweek(test),"1", sep = "-"), "YWw")
[1] "2013-01-07 UTC" "2013-02-04 UTC" "2014-12-15 UTC"
第一个日期应为&#34; 2012-12-31&#34; (2013年第一周的星期一)。 第二个日期应该是&#34; 2013-01-28&#34;和 第三个应该是&#34; 2014-12-08&#34;。
这给了我以下的想法:
> parse_date_time(paste(isoyear(test),isoweek(test),"1", sep = "-"), "YWw") - weeks(1)
[1] "2012-12-31 UTC" "2013-01-28 UTC" "2014-12-08 UTC"
有效,但会在2015年底(第53周)产生错误(NA)。
更确切地说,错误出现在2015-12-28至2016-01-03:
> test <- c("2015-12-27","2015-12-28","2015-12-31","2016-01-01","2016-01-03","2016-01-04")
> parse_date_time(paste(isoyear(test),isoweek(test),"1", sep = "-"), "YWw") - weeks(1)
[1] "2015-12-21 UTC" NA NA NA NA "2015-12-28 UTC"
我找到了一个解决方案&#34; ISOweek&#34;:
> library(ISOweek)
> test <- c("2015-12-27","2015-12-28","2015-12-31","2016-01-01","2016-01-03","2016-01-04")
> ISOweek2date(paste(ISOweek(test),"1", sep = "-"))
[1] "2015-12-21" "2015-12-28" "2015-12-28" "2015-12-28" "2015-12-28" "2016-01-04"