1

So I've been through some Stack Exchange answers, and I can't resolve this.

I have a column in a dataframe that has dates as characters as follows

2011-12
2012-04
2011-10

etc

I would like to convert these to date formats which I have tried to do as follows:

Tots$DatesMerge<-as.Date(Tots$DatesMerge,"%Y-%m")

but I get NA's back all the time.

I tried to do as here but no joy. I'm really not sure what I'm doing wrong.

halfer
  • 19,824
  • 17
  • 99
  • 186
Sebastian Zeki
  • 6,690
  • 11
  • 60
  • 125
  • [This](http://stackoverflow.com/a/6242980/2416535) should work, or the answer above that one. – jakub Dec 01 '16 at 10:08

2 Answers2

4

I'd say as.Date won't be able to work on values where there's no day of the month. You could try with zoo, as long as you don't mind it coming out as a yearmon class:

library( zoo )
as.yearmon( Tots$DatesMerge )

Alternatively, you can specify a day of the month to use as a dummy:

as.Date( paste0( Tots$DatesMerge, "-15" ) )
rosscova
  • 5,430
  • 1
  • 22
  • 35
  • 2
    Are you just copying answers from the duplicated posts mentioned in comments? – Sotos Dec 01 '16 at 10:12
  • No. Sorry if it looks that way. After seeing the comments, I've looked at those links, and yes, they are similar. That's the way things go when there's an answer that works. – rosscova Dec 01 '16 at 10:13
  • Sorry, did I just get a down-vote because my answer happens to be the same as one linked in the comments, and someone thinks I'm "cheating"? – rosscova Dec 01 '16 at 10:14
  • I guess @rosscova answered it and it works so gets the points. – Sebastian Zeki Dec 01 '16 at 10:16
  • It wasn't me but it is obvious that you got the downvote because you answered a dupe question. – Sotos Dec 01 '16 at 10:17
1

Edit: there is already an answer and it is a duplicate, but I suppose the explanation can be useful for further readers, so I'll leave it.

Explanation

This comes from the documentation in R, "Dates are represented as the number of days since 1970-01-01, with negative values for earlier dates".

In R, dates are thus dependent on year, month and days or at least an integer that represent the span (in days) from or to 1970-01-01. As such, the base Dates package in R cannot convert the data formated in years and month into dates since there are no days.

Solution

As a consequence, you have the option, if you go with the base R package, to provide a a day that would be used to convert your data.

Tots$DatesMerge <- as.Date(paste0(Tots$DatesMerge,"01"),"%Y-%m-%d")