Search code examples
rdate-conversion

Convert to date format in r


I have been trying to convert a date from factor format to date format but I've been facing errors every time. The data is of the format

Mon/Yr
201701
201602
201506

Currently the values are factor type. I want to convert them to date format. I've used following code but I've been getting NA values

as.character(x$`Mon/Yr`)
as.POSIXct(x$`Mon/Yr`, format = '%y%m')

Output: [1] NA NA NA

I've followed example solutions from many posts but I'm not able to fix it. Can you please suggest a fix for this?


Solution

  • library(lubridate)
    library(dplyr)
    df <- data.frame("Mon/Yr" = c(201701, 201602, 101506))
    df
    
    > df
      Mon.Yr
    1 201701
    2 201602
    3 101506
    
    df2 <- df %>% 
      dplyr::mutate(Mon.Yr = lubridate::parse_date_time(Mon.Yr, '%Y%m'),
                    Mon.Yr = base::format(Mon.Yr, "%Y-%m"))
    df2
    
    > df2
       Mon.Yr
    1 2017-01
    2 2016-02
    3 1015-06