r 中的复杂日期格式



如果我在Excel中记录了非常复杂的格式,我想知道什么是最佳实践或简洁的代码。例如

bad_format = c(1969*,--1979--,1618, 19.42, 1111983, 1981, 1-9-3-2, 1983, 
“1977”,“1954”, “1943”, 1968, 2287 BC, 1998, ..1911.., 1961)

有各种各样的问题,有些年份被记录为字符串,有些被错误地存储,例如1111983(3 extra 1),其他在BC等。

输出应如下所示:

correct_format = c(1969,1979, 1618, 1942, 1983, 1981, 1932, 1983, 1977, 
1954, 1943, 1968, -2287, 1998, 1911, 1961)

我不知道如何处理这项任务或有能力在 r 中编写可以解决它的代码,但我希望有人可能对如何编写一个可以找到这些问题并纠正它的整洁代码有一个想法。

如果字符串以"BC"结尾,则第一组BC为 TRUE,否则设置为 FALSE。 然后删除非数字并转换为数字给出digits。 最后,如果 TRUE 为 TRUEBC,则使用模数取最后 4 位数字乘以 -1,否则为 +1。

bad_format <- c("1969*", "--1979--", "1618", "19.42", "1111983", "1981", 
"1-9-3-2", "1983", "1977", "1954", "1943", "1968", "2287 BC", "1998", 
"..1911..", "1961")
BC <- grepl("BC$", bad_format)
digits <- as.numeric(gsub("\D", "", bad_format))
ifelse(BC, -1, 1) * (digits %% 10000)

给:

[1]  1969  1979  1618  1942  1983  1981  1932  1983  1977  1954  1943  1968
[13] -2287  1998  1911  1961

我同意@thelatemail,但也许这是一个开始?

bad_format = c("1969*","--1979--","1618", "19.42", "1111983", "1981", "1-9-3-2", "1983",
"“1977”","“1954”", "“1943”", "1968", "2287 BC", "1998", "..1911..", "1961")
# Step 1: Remove trailing/leading characters
# Anchor digits to start with either 1 or 2
ss <- gsub("^.*([12]\d\d\d).*$", "\1", bad_format)
# Step 2: Remove "dividing" non-digit characters
ss <- gsub("\D", "", ss);
#[1] "1969" "1979" "1618" "1942" "1983" "1981" "1932" "1983" "1977" "1954"
#[11] "1943" "1968" "2287" "1998" "1911" "1961"

最新更新