6
votes

In R, I have a vector of strings representing dates in two different formats:

  1. "month/day/year"
  2. "month day, year"

The first format has a two digit year so my vector looks something like this:

c("3/18/75", "March 10, 1994", "10/1/80", "June 15, 1979",...)

I want to put the dates in the vector in a standard format. This should be easy with the mdy function from the lubridate package, except when I pass it the first format, it returns an unwanted century.

mdy("3/18/75") returns "2075-03-18 UTC"

Does anyone know how it can return the date in the 20th century? That is "1975-03-18 UTC". Any other solution of how to standardize the dates will be greatly appreciated as well.

I am running version lubridate_1.3.3 if that matters.

4
Interesting. as.Date("3/18/75", "%m/%d/%y") returns the correct century. The lubridate origin is the standard 1970 origin as well. Weird.Rich Scriven
Here is a brilliant reply to this problem: stackoverflow.com/a/12957909/7941188tjebo
This is not an issue running lubridate v 1.7.1AdamO

4 Answers

1
votes

You can use a postprocessing function to adjust the century threshold:

library(lubridate)
dates <- c("3/18/75", "March 10, 1994", "10/1/80", "June 15, 1979", "10/19/15")

adjustCentury <- function(d, threshold=1930){
  y <- year(d) %% 100
  if(y > threshold %% 100) year(d) <- 1900 + y
  d
}

lapply(lapply(dates, mdy), adjustCentury)

results in:

[[1]]
[1] "1975-03-18 UTC"

[[2]]
[1] "1994-03-10 UTC"

[[3]]
[1] "1980-10-01 UTC"

[[4]]
[1] "1979-06-15 UTC"

[[5]]
[1] "2015-10-19 UTC"
1
votes

You could do it like this:

some_dates <- c("3/18/75", "March 10, 1994", "10/1/80", "June 15, 1979")
dates <- mdy(some_dates)
future_dates <- year(dates) > year(Sys.Date())
year(dates[future_dates]) <- year(dates[future_dates]) - 100

Maybe a better approach would be to remove the ambiguity from your date strings though -- otherwise your code will be wrong when 2075 rolls around ;)

library(stringr)
some_dates <- c('3/18/75', '01/09/53')
str_replace(some_dates, '[0-9]+$', '19\\0')

Or if the two date strings are mixed:

some_dates <- c("3/18/75", "March 10, 1994", "10/1/80", "June 15, 1979")
str_replace(some_dates, '/([0-9]{2}$)', '/19\\1')
1
votes

lubridate v1.7.4 does. Looking at a 2068 as we speak

-1
votes

Lubridate v1.7.1 does not have this issue.