2

I'm using R to analyze some data and I have this data set and I'm trying to get a subset of the data that is only using the most current dates. I'm having trouble doing this and some of my dates have different formats.

ex. 10/01/00 10/01/00 10/20/2000 05/13/2000

How can I get these to be all the same format?

Keeper01
  • 25
  • 5
  • 1
    I seem to remember that the 'lubridate' package has some facilities for date format guessing. If it's just two different formats it would seem a simple matter to first fix the "short ones" and then convert. – IRTFM Nov 14 '14 at 20:17
  • Welcome to Stack Overflow! To help debug the problem, it would help to see the input, and what it outputs. – Jonathan Nov 14 '14 at 20:30
  • Does this answer your question? [How to change multiple Date formats in same column](https://stackoverflow.com/questions/13764514/how-to-change-multiple-date-formats-in-same-column) – OTStats Dec 30 '19 at 00:49

2 Answers2

1

You could try guess_formats from lubridate

x <- c("10/01/00", "10/01/00", "10/20/2000", "05/13/2000")
library(lubridate)
as.Date(x, guess_formats(x, "mdy"))
# [1] "2000-10-01" "2000-10-01" "2000-10-20" "2000-05-13"
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
0

If they are all 2000 or later try this:

x <- c("10/01/00", "10/01/00", "10/20/2000", "05/13/2000") # test data

xx <- as.Date(sub("/(..)$", "/20\\1", x)); xx
## [1] "10/01/2000" "10/01/2000" "10/20/2000" "05/13/2000"

If the objective is to take the most recent date then this will work whether or not the dates are all 2000 or later provided there is no date more than 100 years old. Assuming we have already run the above line if all the dates are in the future then the most recent date must be in the 1900s so repeat the sub but with 19 instead of 20 and take the max; otherwise, the max date must be 20xx so remvove the dates in the future and take the max of what is left:

if (all(xx > Sys.Date()) max(as.Date(sub("/(..)$", "/19\\1", x)))
else max( xx[xx <= Sys.Date()] )

Update Some improvements.

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341