问题是因为 for %u
, 1
isMonday
和7
isSunday
是一周的。%U
假设星期从星期日开始这一事实使问题更加复杂。
对于 的给定输入和预期行为format = "%Y-%U-%u"
,第 4 行的输出与前 3 行的输出一致。
也就是说,如果你想使用format = "%Y-%U-%u"
,你应该预处理你的输入。在这种情况下,第四行必须as.Date("2016-51-7", format = "%Y-%U-%u")
由
format(as.Date("2016-12-18"), "%Y-%U-%u")
# "2016-51-7"
相反,您当前正在通过"2016-50-7"
.
更好的方法可能是使用Uwe Block 的回答中建议的方法。"2016-50-4"
由于您对转换为感到满意,因此"2016-12-15"
我怀疑在您的原始数据中,星期一也算在内1
。您还可以创建一个自定义函数,将 的值更改%U
为计算周数,就像一周从星期一开始一样,以便输出符合您的预期。
#Function to change value of %U so that the week begins on Monday
pre_process = function(x, delim = "-"){
y = unlist(strsplit(x,delim))
# If the last day of the year is 7 (Sunday for %u),
# add 1 to the week to make it the week 00 of the next year
# I think there might be a better solution for this
if (y[2] == "53" & y[3] == "7"){
x = paste(as.integer(y[1])+1,"00",y[3],sep = delim)
} else if (y[3] == "7"){
# If the day is 7 (Sunday for %u), add 1 to the week
x = paste(y[1],as.integer(y[2])+1,y[3],sep = delim)
}
return(x)
}
用法是
as.Date(pre_process("2016-50-7"), format = "%Y-%U-%u")
# [1] "2016-12-18"
我不太确定如何在星期天结束一年。