正则表达式 - 在月份和日期 R 中否定零
regexp - negate zeros in months and days R
我有许多来自 USGS 网站的日期向量。
一些日期看起来像这样:
“1981-00-00”,或者像这样:“1981-01-00”。
我想找到这些不可能的日期,然后在我有“00”的地方放上“01”。
这就是我所做的:
date <- c("1981-01-23","1981-00-02","2000-01-00","1900-00-00","1999-12-31")
month_regex <- "0?[1-9]|1[0-2]"
day_regex <- "0?[1-9]|[12]\d|30|31"
tmp_date <- as.character(date)
tmp_month <- substr(tmp_date,6,7)
if (!all(grepl(month_regex,tmp_month))){
substr(tmp_date[!grepl(month_regex,tmp_month)],6,7) <- "01"
}
tmp_day <- substr(tmp_date,9,10)
if (!all(grepl("0?[1-9]|[12]\d|30|31",tmp_day))){
substr(tmp_date[!grepl("0?[1-9]|[12]\d|30|31",tmp_day)],9,10) <- "01"
}
print(tmp_date)
它似乎可以工作,但我想知道是否可以通过替换在一两行中实现这一点。
我在考虑这些方面的事情:
grepl(".+[-](?!00).+[-](?!00).+",tmp_date,perl = TRUE)
但无法让它发挥作用。
由于您想替换 -00
的任何位置,相对简单的 gsub("-00","-01",x)
应该可行:
date1 <- c("1981-01-23","1981-00-02","2000-01-00",
"1900-00-00","1999-12-31")
date1.fix <- gsub("-00","-01",date1)
##[1] "1981-01-23" "1981-01-02" "2000-01-01" "1900-01-01" "1999-12-31"
如果这 不 对你有用,或者结果不是你想要的,你必须将你的问题编辑为 clarify/give 一个可重现的例子什么不起作用...
我有许多来自 USGS 网站的日期向量。 一些日期看起来像这样: “1981-00-00”,或者像这样:“1981-01-00”。 我想找到这些不可能的日期,然后在我有“00”的地方放上“01”。 这就是我所做的:
date <- c("1981-01-23","1981-00-02","2000-01-00","1900-00-00","1999-12-31")
month_regex <- "0?[1-9]|1[0-2]"
day_regex <- "0?[1-9]|[12]\d|30|31"
tmp_date <- as.character(date)
tmp_month <- substr(tmp_date,6,7)
if (!all(grepl(month_regex,tmp_month))){
substr(tmp_date[!grepl(month_regex,tmp_month)],6,7) <- "01"
}
tmp_day <- substr(tmp_date,9,10)
if (!all(grepl("0?[1-9]|[12]\d|30|31",tmp_day))){
substr(tmp_date[!grepl("0?[1-9]|[12]\d|30|31",tmp_day)],9,10) <- "01"
}
print(tmp_date)
它似乎可以工作,但我想知道是否可以通过替换在一两行中实现这一点。 我在考虑这些方面的事情:
grepl(".+[-](?!00).+[-](?!00).+",tmp_date,perl = TRUE)
但无法让它发挥作用。
由于您想替换 -00
的任何位置,相对简单的 gsub("-00","-01",x)
应该可行:
date1 <- c("1981-01-23","1981-00-02","2000-01-00",
"1900-00-00","1999-12-31")
date1.fix <- gsub("-00","-01",date1)
##[1] "1981-01-23" "1981-01-02" "2000-01-01" "1900-01-01" "1999-12-31"
如果这 不 对你有用,或者结果不是你想要的,你必须将你的问题编辑为 clarify/give 一个可重现的例子什么不起作用...