r中的复杂日期格式

问题描述 投票:1回答:2

如果我在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个额外的1),其他在BC等。

输出应该像这样:

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

我不知道如何处理此任务,或者不具备在r中编写可以解决该问题的代码的能力,但我希望有人可能对如何编写可以发现这些问题并加以纠正的简洁代码有所了解。 。

r date format complextype
2个回答
3
投票

如果字符串以BC结尾,则首先将"BC"设置为TRUE,否则为FALSE。然后删除非数字并转换为数字,得到digits。最后,如果BC为TRUE,则使用模取最后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

1
投票

我同意@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"
© www.soinside.com 2019 - 2024. All rights reserved.