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

Viewed 59
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"?

2 Answers

Not that I know of, but you could define your own function to handle it.
Here I take the year-month portion of the date and then add the number of days on and let it wrap into the next month (or even year) if required.

# two invalid, one valid date
x <- c("2011-11-31", "2000-04-31", "2010-01-10", "2011-12-32")

parse_bad_dates <- function(x) {
  as.Date(paste(substr(x, 1, 7), "1"), format="%Y-%m %d") +
  as.numeric(substr(x, 9, 10)) - 1
}

parse_bad_dates(x)
#[1] "2011-12-01" "2000-05-01" "2010-01-10" "2012-01-01"

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"
Related