Home > Blockchain >  Changing date formats from MM-YYYY to DD-MM-YYYY by creating random DD
Changing date formats from MM-YYYY to DD-MM-YYYY by creating random DD

Time:01-26

I have a dataset that has a variable date_of_birth (MM-YYYY). I would like to change this format to DD-MM-YYYY by creating random DD for each observation.

df1 <- as.Date(paste0(df,"01/",MMYYYY),format="%d-%m-%Y")

CodePudding user response:

dates <- c("02-1986", "03-1990")

add_random_day <- function(date) {
  date <- lubridate::as_date(date, format="%m-%Y")
  days_in_month <- lubridate::days_in_month(date)
  random_day <- sapply(days_in_month, sample, size = 1)
  lubridate::day(date) <- random_day
  date
}

add_random_day(dates)
  • Related