我正在使用旧的日期格式,其中前两位数字代表 20 世纪的年份。前两位小数是月份(即 01-12),第三位和第四位小数是该月中的日期(即 01-31)。问题在于以零结尾的日期(即 10、20、30)会删除尾随零,因此某些日期格式仅具有三位小数。
如何恢复尾随零,以便可以将此旧日期格式转换为现代日期格式(即 yyyy-mm-dd)?
例子:
library(tidyverse)
# Example data
xx <- data.frame(yr_mo_da = c('89.1208','89.1209','89.121', '89.1211'))
# My attempt to extract year, month, day from the old date format
# NOTE how the day is not extracted properly because there is not a fourth decimal place on Dec. 10
xx$year <- as.numeric(gsub("\\..*","",xx$yr_mo_da))
xx$month <- as.numeric(sub("^[0-9]+\\.([0-9]{2}).*", "\\1", xx$yr_mo_da))
xx$day <- as.numeric(sub("^[0-9]+\\.[0-9]{2}([0-9]{2}).*", "\\1", xx$yr_mo_da))
xx
#> yr_mo_da year month day
#> 1 89.1208 89 12 8.000
#> 2 89.1209 89 12 9.000
#> 3 89.121 89 12 89.121
#> 4 89.1211 89 12 11.000
# Create modern date format
xx <- xx %>%
mutate(year = year + 1900,
Date = make_date(year,month,day)) %>%
select(-c(yr_mo_da,year,day,month))
xx
#> Date
#> 1 1989-12-08
#> 2 1989-12-09
#> 3 <NA>
#> 4 1989-12-11
正确的输出应该如下所示:
xx
#> Date
#> 1 1989-12-08
#> 2 1989-12-09
#> 3 1989-12-10
#> 4 1989-12-11
创建于 2023-09-05,使用reprex v2.0.2
您可以首先用“0”右填充这些字符串:
创建于 2023-09-05,使用reprex v2.0.2
在解析之前,您需要将数字数据转换回文本。仅使用基本 R 的一种方法是:
如果您最初的分配没有强制字符值,我们可以跳过 double
as.numeric()
。