为什么解析“%Y-%m”在R中使用strptime得到NA结果,但是“%Y-%m-%d”作品? [英] Why is parsing "%Y-%m" using strptime in R giving an NA result, but "%Y-%m-%d" works?
问题描述
如果我使用 strptime
与一年和一年格式的%Y-%m(如2009-12),我得到NA结果。但是如果我添加一个2009-12-01一天,并相应地更改格式字符串,我会得到一个结果。示例:
> strptime(2009-12,format =%Y-%m)
pre>
[1] NA
> strptime(2009-12-03,format =%Y-%m-%d)
[1]2009-12-03
为什么这样?
更新:我很好奇大概是为什么strptime不解析一年和一个月,因为它似乎不奇怪的原因是它不会这样做是因为它仅解析一年,或一年一次-day:
> strptime(2009,format =%Y)#年。作品。使用当前月份和日期作为默认值。
[1]2009-12-02
> strptime(2009-03,format =%Y-%d)#年和日。作品。将当前月份用作默认值。
[1]2009-12-03
> strptime(2009-03,format =%Y-%m)#年和月。不行?
[1] NA
更新以解释为什么这不是重复的
可能的重复在这个问题后几年被问到,它涉及到一个单独的API在R
:asDate
函数。这个问题是关于strptime
函数的一个怪癖,其中R
3.1.3仍然适用。解决方案对我来说似乎是明智的行为。正如我所看到的,一个更好的问题将是为什么它允许你这样做:
strptime(2009-03,format =%Y-%d)
?
以下是解决我想要实现的解决方法(即,具有指定的月份和年份但今天的POSIXlt对象):
as.POSIXlt(paste(2009-12,days(Sys.Date()),sep = - ) )
I'm getting a result I don't understand in R.
If I use
strptime
with a year and day formatted %Y-%m (like "2009-12"), I get an NA result. But if I add a day, like "2009-12-01", and change the format string accordingly, I do get a result. Example:> strptime("2009-12",format="%Y-%m") [1] NA > strptime("2009-12-03",format="%Y-%m-%d") [1] "2009-12-03"
Why is that?
Update: The thing I'm curious about is why strptime doesn't parse a year and a month, and the reason it seems weird that it wouldn't do so is because it does parse a year only, or a year-and-a-day:
> strptime("2009",format="%Y") # year only. Works. Uses current month and day as defaults. [1] "2009-12-02" > strptime("2009-03",format="%Y-%d") # year and day. Works. Uses current month as default. [1] "2009-12-03" > strptime("2009-03",format="%Y-%m") # year and month. Doesn't work. ? [1] NA
Update to explain why this is not a duplicate The possible duplicate was asked a few years after this question and it is concerned with a separate API in
R
: theasDate
function. This question is about a quirk of thestrptime
function that as ofR
3.1.3 still applies.解决方案That seems like sensible behavior to me. As I see it, a better question would be "why does it allow you to do this:
strptime("2009-03",format="%Y-%d")
?"Here's a workaround to get what I think you're trying to achieve (i.e. a POSIXlt object with a specified month and year, but today's day):
as.POSIXlt(paste("2009-12", days(Sys.Date()), sep="-"))
这篇关于为什么解析“%Y-%m”在R中使用strptime得到NA结果,但是“%Y-%m-%d”作品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!