user12959781
user12959781

Reputation: 5

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

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

Upvotes: 0

Views: 37

Answers (1)

Andrea Barghetti
Andrea Barghetti

Reputation: 126

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)

Upvotes: 0

Related Questions