3

How would I convert the following character variables to dates?

strDates <- c("Jan.2008", "Feb.2008") str(strDates) chr [1:2] "Jan.2008" "Feb.2008" dates <- as.Date(strDates, "%b %Y") str(dates) Date[1:2], format: NA NA 

Any assistance would be greatly appreciated

1
  • 1
    If you are dealing with months and not really dates you might be better off using the yearmon class located in the zoo package in which case you don't have to deal with days of the month in the first place: as.yearmon(strDates, "%b.%Y") Commented Feb 17, 2012 at 13:49

2 Answers 2

2

To form a valid 'date', you also need a day which your data was lacking. So we add one, and we simply use an arbitrary day (here: first of the month):

R> strDates <- c("Jan.2008", "Feb.2008") R> strptime(paste("01", strDates), "%d %b.%Y") [1] "2008-01-01" "2008-02-01" R> 
Sign up to request clarification or add additional context in comments.

1 Comment

Anyone know whether lubridate has any conversion function which assumes "day = 1" in the absence of a day field?
1

A Date requires a day element as well, so you can add that to the input string with paste:

full.dates <- paste("01", strDates, sep = ".") 

Specify the template correctly, including separator tokens:

as.Date(full.dates, "%d.%b.%Y") [1] "2008-01-01" "2008-02-01" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.