r 中的复杂日期格式
Complex date formatting in 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 中编写可以解决它的代码,但我希望有人可能知道如何编写可以找到这些问题的简洁代码并更正。
我同意@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"
如果字符串以 "BC"
结尾,则首先将 BC
设置为 TRUE,否则设置为 FALSE。然后删除 non-digits 并转换为数字 digits
。如果 BC
为真,最后使用模数将最后 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
如果我在 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 中编写可以解决它的代码,但我希望有人可能知道如何编写可以找到这些问题的简洁代码并更正。
我同意@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"
如果字符串以 "BC"
结尾,则首先将 BC
设置为 TRUE,否则设置为 FALSE。然后删除 non-digits 并转换为数字 digits
。如果 BC
为真,最后使用模数将最后 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