在 r lubridate 中将字符格式转换为日期格式,领先年份 20 而不是 19

convert character format to date format in r lubridate, leading year 20 not 19

我需要使用 lubridate 将 Marriage 内置数据集中的 dob 列的 fctr 格式(例如 4/11/64)转换为日期格式。我尝试了很多函数,strptime,as_date等,但是4/11/64变成了2064年,这对于1964年出生的人来说是不正确的。有没有自动将年份转换为19xx的函数?或者我必须在转换之前先把前导“19”放在字符格式中?

我认为你必须自己添加“19”,除非你想使用 hydrostats::four.digit.year:

hydrostats::four.digit.year(dmy("4/11/64"), year=1900)

(函数只有几行,不想依赖包的直接copy即可)

function (x, year = 1968)  {
    n <- as.numeric(strftime(x, format = "%y"))%%100
    Y <- ifelse(n > year%%100, 1900 + n, 2000 + n)
    return(Y)
}

否则,您将受制于 POSIX 标准。 "%y" 是转换两位(或一位)数字年份的标准标签,从 ?strptime:

‘%y’ Year without century (00-99). On input, values 00 to 68 are prefixed by 20 and 69 to 99 by 19 - that is the behaviour specified by the 2018 POSIX standard, but it does also say ‘it is expected that in a future version the default century inferred from a 2-digit year will change’.

标准本身可用 here:

If century is not specified, then values in the range [69,99] shall refer to years 1969 to 1999 inclusive, and values in the range [00,68] shall refer to years 2000 to 2068 inclusive.

另请参阅: