我在将每周日期转换为每月日期时遇到麻烦,从看起来像这样的字符串开始
tt <- c("2009-24-1", "2001-10-1", "2000-16-1", "2013-18-1", "2015-21-1",
"2015-53-1", "2009-53-1")
我认为这个日期的正确格式应该是format = "%Y-%V-%u"
,因为R文档产生
%V
Week of the year as decimal number (01–53) as defined in ISO 8601.
然而,不幸的是,当我尝试转换为日期时,它不起作用
as.Date(tt, format = "%Y-%V-%u", origin = "1970-01-01")
# "2009-02-21" "2001-02-21" "2000-02-21" "2013-02-21" "2015-02-21" "2015-02-21" "2009-02-21"
显然是不正确的。然后我尝试使用%U
%U
Week of the year as decimal number (00–53) using Sunday as the first day 1 of the week
由于我所有的日期都是从星期一开始的周日期,这也不正确,但至少产生了一些正确的日期和一些NAs。
as.Date(tt, format = "%Y-%U-%u", origin = "1970-01-01")
# "2009-06-15" "2001-03-12" "2000-04-17" "2013-05-06" "2015-05-25" NA NA
我感谢任何能解决这个问题的想法(最好不使用包)。
在?strptime
帮助页面上,它说%V是接受的,但在输入时被忽略。相反,使用ISOweek包将tt
转换为Date类,然后通过使用"%Y-%V-%u"问题中给出的格式(使用%V作为输出而不是输入,因此应该可以工作)。请注意,ISOweek2date
期望周数以W开头,因此使用sub
插入。
library(ISOweek)
date <- ISOweek2date(sub("-", "-W", tt))
# converting date back to ISOweek using format in question should give back tt
identical(format(date, "%Y-%V-%u"), tt)
## [1] TRUE
使用strptime
显示问题。
strptime(tt, "%Y-%U-%u", tz="UTC")
# [1] "2009-06-15 UTC" "2001-03-12 UTC" "2000-04-17 UTC"
# [4] "2013-05-06 UTC" "2015-05-25 UTC" NA
# [7] NA
# Warning messages:
# 1: In strptime(tt, "%Y-%U-%u", tz = "UTC") :
# (0-based) yday 368 in year 2015 is invalid
# 2: In strptime(tt, "%Y-%U-%u", tz = "UTC") :
# (0-based) yday 368 in year 2009 is invalid