[英]Unable to convert Month-Year string to Date in R
I'm using as.Date
to convert a string like Aug-2002
to a dates object representing just the month of Aug of 2002, or if a day must be specified, Aug 1, 2002. 我正在使用as.Date
将类似Aug-2002
的字符串转换为as.Date
Aug-2002
的月份的dates对象,或者如果必须指定日期,即2002年8月1日。
However 然而
> as.Date(c('07-2002'), "%M-%Y")
[1] "2002-11-06"
> as.Date(c('Aug-2002'), "%b-%Y")
[1] NA
Why does the first line of code convert it to a different month and day? 为什么第一行代码将其转换为不同的月份和日期? And the second one is NA
? 第二个是NA
?
I referred to this table for the formatting symbols. 我参考了此表中的格式符号。
The problem you are having is that the dates you have do not have a day value. 您遇到的问题是您拥有的日期没有日期值。 Without the day value the format="%m-%Y" will not work in as.Date. 没有日期值,格式=“%m-%Y”将无法在as.Date中使用。 These options below will solve them: 以下这些选项将解决它们:
as.Date(paste0('01-', c('07-2002')), format="%d-%m-%Y")
library(zoo) #this is a little more forgiving:
as.yearmon(c('07-2002'), "%m-%Y")
as.yearmon(c('Aug-2002'), "%b-%Y")
as.Date(as.yearmon(c('07-2002'), "%m-%Y"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.