Bjo*_*erg 3 r date data-conversion redcap
我正在尝试从数字中提取日期。日期存储为 11 位个人 ID 号(日期-月份-年)的前 6 位数字。不幸的是,基于云的数据库 (REDCap) 输出被格式化为数字,因此每月前 9 天出生的人的前导零最终会变成 10 位数字的 ID 号码,而不是 11 位数字。我设法提取了与日期相对应的 6 或 5 位数字,即 311230 代表 1930 年 12 月 31 日,或 11230 代表 1930 年 12 月 1 日。我最终遇到了两个无法解决的问题。
假设我们使用以下数字:
dato <- c(311230, 311245, 311267, 311268, 310169, 201104, 51230, 51269, 51204)
Run Code Online (Sandbox Code Playgroud)
我将它们转换为字符串,然后应用 as.Date() 函数:
datostr <- as.character(dato)
datofinal <- as.Date(datostr, "%d%m%y")
datofinal
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是:
我确信这对于那些对 R 有更多了解的人来说一定很容易,但是,我在解决这个问题上有点困难。任何帮助是极大的赞赏。
问候比约恩
如果您的 5 位数字确实只需要补零,那么
dato_s <- sprintf("%06d", dato)
dato_s
# [1] "311230" "311245" "311267" "311268" "310169" "201104" "051230" "051269" "051204"
Run Code Online (Sandbox Code Playgroud)
从那里,你关于“1969 年之前的日期”的问题,看看?strptime模式'%y':
'%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'.
Run Code Online (Sandbox Code Playgroud)
因此,如果您有特定的交替年份,则需要在发送到之前as.Date添加世纪(使用strptime-patterns)。
'%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'.
Run Code Online (Sandbox Code Playgroud)
在本例中,我假设 50-99 为 1900,其他均为 2000。如果您需要 40 秒或 30 秒,请随意调整模式:将数字添加到第二个模式(例如[3-9])并从第一个模式中删除(例如,[0-2]),确保所有十年都包含在一种模式中,而不是“两者都不是”。
借用艾伦的回答,我喜欢这个假设now()(因为你确实提到了“出生于”)。没有lubridate,试试这个:
dato_d <- as.Date(gsub("([0-4][0-9])$", "20\\1",
gsub("([5-9][0-9])$", "19\\1", dato_s)),
format = "%d%m%Y")
dato_d
# [1] "2030-12-31" "2045-12-31" "1967-12-31" "1968-12-31" "1969-01-31" "2004-11-20"
# [7] "2030-12-05" "1969-12-05" "2004-12-05"
Run Code Online (Sandbox Code Playgroud)