regexp-在月份和天数R中对零求反
我有很多美国地质调查局网站上的数据载体。 有些日期如下所示: “1981-00-00”,或者类似这样:“1981-01-00”。 我想找出这些不可能的日期,只要把“01”放在我有“00”的地方。 这就是我所做的:regexp-在月份和天数R中对零求反,r,regex,date,regex-negation,R,Regex,Date,Regex Negation,我有很多美国地质调查局网站上的数据载体。 有些日期如下所示: “1981-00-00”,或者类似这样:“1981-01-00”。 我想找出这些不可能的日期,只要把“01”放在我有“00”的地方。 这就是我所做的: 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]
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)
但无法使其正常工作。由于您希望在找到它的任何位置替换
-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"
date1读得不太仔细,但是gsub(“-00”,“-01”,date\u字符串)”有什么问题吗@谢谢你。我现在尝试了:sapply(tmp_date,function(x)gsub(“-01”,“-00”,x))@BenBolker我得到了一个命名向量,其中的名称是正确的日期,值是原始的错误日期。
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"