在R语言处理调查数据时,自定义两位年份转日期的世纪前缀
解决两位年份前缀自定义转换的问题
默认as.Date(..., format='%m/%d/%y')的年份转换规则是00-69映射到2000-2069,70-99映射到1970-1999,不符合你要的≤23用20前缀、其余用19前缀的需求,这里提供两种可行方案:
方案一:基础R原生处理
拆分原日期字符串,手动判断年份后拼接转换:
# 提取两位年份并转数值 hd$year_num <- as.numeric(substr(hd$DOB, nchar(hd$DOB)-1, nchar(hd$DOB))) # 生成四位年份 hd$year_four <- ifelse(hd$year_num <= 23, paste0("20", substr(hd$DOB, nchar(hd$DOB)-1, nchar(hd$DOB))), paste0("19", substr(hd$DOB, nchar(hd$DOB)-1, nchar(hd$DOB)))) # 拼接完整日期字符串并转Date类型 hd$DOB_new <- as.Date(paste0(substr(hd$DOB, 1, nchar(hd$DOB)-2), hd$year_four), format = "%m/%d/%Y")
方案二:用lubridate包简化操作
lubridate的parse_date_time函数支持自定义cutoff_year参数,直接指定分界年份:
library(lubridate) # 解析日期,cutoff_year=2023表示两位年份≤23时用20前缀,否则用19前缀 hd$DOB_new <- parse_date_time(hd$DOB, orders = "mdy", cutoff_year = 2023) # 如需转为Date类型而非POSIXct,执行下面一行 hd$DOB_new <- as.Date(hd$DOB_new)
内容的提问来源于stack exchange,提问作者Allison
相关产品推荐
相关产品推荐

