Convert column by formating like date

I want to convert 02/01/12 to 02-01-2012
where 02 are month 01 day and 2012 year

It is simple enough to manipulate the initial string into another string but it will not have a Date value. Dates, as far as I know, are always displayed in R as YYYY-MM-DD.

DF <- data.frame(Date = c("02/01/12", "01/31/12"))
DF$Date <- sub("(\\d{2})/(\\d{2})/(\\d{2})", "\\1-\\2-20\\3", DF$Date)
#>         Date
#> 1 02-01-2012
#> 2 01-31-2012

DF2 <- data.frame(Date = c("02/01/12", "01/31/12"))
DF2$Date <- as.Date(DF2$Date, format = "%m/%d/%y")
#>         Date
#> 1 2012-02-01
#> 2 2012-01-31

Created on 2023-02-19 with reprex v2.0.2

I think something like this will do it. However, it gives you a character variable not an actual date variable. Is this what you want?

(mydate <-  mdy("02/01/12"))


(newdate  <- format(mydate, "%d/%m/%Y"))

As well as @FJCC 's DF2

#> [1] "2012-02-01"

which is a date object.

Unless compelled to use a data frame or other R object for both calculation and presentation, it is far less trouble in the long run to process it through a report generator, such as {gt}, many of which have built-in functions to handle these chores. Too often, trying to mix data and presentation results in flawed solutions to both problems.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.