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,824
  • 17
  • 99
  • 186
Mahrokh
  • 93
  • 1
  • 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
  • Agree. I got a column with 2020-03 which is YYYY-MM format. When importing, R reads it as a character. So i can do these two steps in one formula but let me break down into two steps: # this is to add the day behind the YYYY-mm step 1. Data$Date2 <- paste0(Data$date, "-1") #this follows the format of the character (given in hyphens) so it converts accordingly step 2. Data$Date3 <- as.Date(Data$Date2, "%Y-%m-%d") – Law Val Jun 14 '22 at 15:37

0 Answers0