Skip to content
Prev 386928 / 398503 Next

Help with changing date format in R

Hi,

Internally, once you have a Date class object in R, the "printed" output displayed will be the default, which I believe is influenced by your locale. See ?format.Date.

That being said, in your example data below, 07022020, could be either July 2, 2020, or February 7, 2020. How do you know which one is correct, since both are legal conversions?

Thus, you need some other flag value to determine which conversion is correct.

Can you use the observer values as a flag?

If so, then you can use a conditional statement (e.g. ?ifelse) to make the conversion.

For example:

  d$date <- ifelse(d$observer %in% c(vector, of, observers), 
                   as.Date(d$date, format = "%d%m%Y"),
                   as.Date(d$date, format = "%m%d%Y"))

Also, you might not want to overwrite the original values, and create a new column, in the case of errors.

Regards,

Marc Schwartz