Search code examples
rlubridate

how to arrange false(no exist) character column to date in r?(similar Converting character column to Date in r)


ymd("2011-11-31") 
All formats failed to parse. No formats found.[1] NA

2011-11 have 30 days not 31 so ymd get failed state. My data have some false date in date column like this and I want to learn elegant way to handle. is there any package or function that data to turn like this "2011-12-01"?


Solution

  • Similar answer here but works with rolling months and years too

    library(lubridate)
    d <- c("2011-11-31",'2011-13-04','2011-12-32')
    
    parse_false_date <- function(d) {
      x <- strcapture("(\\d{4})-(\\d{2})-(\\d{2})", d, 
        data.frame(y=integer(),m=integer(),d=integer()))
      make_date(x$y)+months(x$m-1)+days(x$d-1)
    }
    
    parse_false_date(d)
    #> [1] "2011-12-01" "2012-01-04" "2012-01-01"