0

Given two dates in a data frame that are in this format:

 df <- tibble(date = c('25/05/95', '21/09/18'))
 df$date <- as.Date(df$date)

How can I convert the dates into this format - date = c('1995-05-25', '2018-09-21') with the year appearing first and in four digit format, and by only using base R?

Here is my attempt, I successfully reversed the order, but still wasn't able to express the year in 4 digit format:

df <- tibble(date_orig = c('25/05/1995', '21/09/2018'))
df$date <- as.Date(df$date_orig)
year_date <-  format(df$date, '%d')
month_date <- format(df$date, '%m')
day_date <- format(df$date, '%y')
df$newdate <- as.Date(paste(paste(year_date, month_date, sep = '-'), day_date, sep = '-'))
df$newdate_final <- as.Date(df$newdate, '%Y-%m-%d')
user213544
  • 2,046
  • 3
  • 22
  • 52
pd441
  • 2,644
  • 9
  • 30
  • 41

1 Answers1

1

You need to know which format your date follows and find it in ?strptime to convert it in date object. As you required output is the standard way to represent dates you would not need format.

as.Date(df$date, "%d/%m/%Y")
#[1] "1995-05-25" "2018-09-21"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213