R Lubridate Returns 给定两位数年份时不需要的世纪

R Lubridate Returns Unwanted Century When Given Two Digit Year

R 中,我有一个以两种不同格式表示日期的字符串向量:

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

第一种格式有两位数的年份,所以我的矢量看起来像这样:

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

我想以标准格式将日期放入向量中。使用 lubridate 包中的 mdy 函数应该很容易,除了当我传递第一种格式时,它 return 是一个不需要的世纪。

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

有谁知道 return 20 世纪的日期是怎么来的?即“1975-03-18 UTC”。任何其他关于如何标准化日期的解决方案也将不胜感激。

我是 运行 版本 lubridate_1.3.3 如果重要的话。

你可以这样做:

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

也许更好的方法是从您的日期字符串中消除歧义——否则当 2075 年到来时您的代码将是错误的 ;)

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

或者如果两个日期字符串混合:

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

您可以使用后处理函数来调整世纪阈值:

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)

结果:

[[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"

Lubridate v1.7.1 没有这个问题。

lubridate v1.7.4 支持。边说边看2068