nestorthecat nestorthecat - 8 days ago 6
R Question

Converting nonstandard string dates into date objects in R

I have a dataframe that contains a column V8 which consists of string values in this format --

7/16, 02/11, 5/12


These items are dates, the first representing the month of July in the year 2016, the second representing February of 2011, and the last representing May 2012. Sometimes there are initial zeroes, other times there are not.

I would like to represent these dates as such in R using the
as.Date
method, but I know that this representation is nonstandard and ambiguous.

I was going to resort to programmatically converting the values in the CSV file to representations that would be understood by
as.Date
, but it struck me that this must be a common problem so there might be a less involved and more idiomatic solution. I found the
strptime
function but I am not clear on how to use it, tried
strptime("09/12", format="%m/%y")
but it returns
NA
.

How can I convert these non-standard string values into Date objects?

Answer

One option would be to use as.Date() and assume that each of your months occurs on the first of the month:

> strDates <- c("07/16", "02/11", "05/12")
> dates <- as.Date(paste0("01/", strDates), "%d/%m/%y")
> dates
[1] "2016-07-01" "2011-02-01" "2012-05-01"