简体   繁体   中英

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.

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 ?

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. 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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM