0

I have trouble converting a character column with YYYY-MM format to date types in R. I have already tried different approaches to address this but none worked.

    dateC = "2001-01"
    # Method I)
    dateF <- as.factor(dateC) # returns factor: "2001-1"
    dateD <- as.Date(dateF,format="%Y-%m") # returns NA
    # Method II) 
    dateI <- as.double(dateC) # returns NA
    dateD <- as.Date(dateI,format="%Y-%m") # returns NA

The method I) works when the character column is in YYYY-MM-DD format, however not for year and month ones.

Method II) is not working for either of the formats. I somehow managed to change the characters to integer (with some random function that I do not remember now!) and then applied as.date() but that did not work either.

halfer
  • 19,471
  • 17
  • 87
  • 173
Mahrokh
  • 63
  • 5
  • 3
    A date object contains a year, month and day. Try: `as.Date(paste(dateF, 1) , format="%Y-%m %d")`, this will set every conversion to the first of the month. – Dave2e Mar 15 '20 at 17:52
  • It does and it worked! Thanks! So based on what you said, R does not recognize year-month is as a date object, right? There has to be a "day" element too. Am I right? – Mahrokh Mar 15 '20 at 18:47
  • 1
    Yes correct! A date has to have a day, month and year. – Dave2e Mar 15 '20 at 18:58

0 Answers0