我有以下日期向量,格式为m / d / y:
(dates<-c("1/31/2018", "2/31/2018", "3/0/2018", "4/31/2018", "9/5/2018"))
[1] "1/31/2018" "2/31/2018" "3/0/2018" "1/5/2018"
如果仔细看,其中一些日期是无意义的-例如。 2月没有31天,0并非该月的有效日期。我想将全天值替换为“ 1”。我希望结果如下所示:
dates
[1] "1/1/2018" "2/1/2018" "3/1/2018" "4/1/2018" "9/1/2018"
答案 0 :(得分:4)
要转换不良代码,请仅先尝试转换为Date
类,如果这使NA不可用,请替换中间部分。
ifelse(is.na(as.Date(dates, "%m/%d/%Y")), sub("/.*/", "/1/", dates), dates)
## [1] "1/31/2018" "2/1/2018" "3/1/2018" "4/1/2018" "9/5/2018"
或将它们全部转换:
sub("/.*/", "/1/", dates)
## [1] "1/1/2018" "2/1/2018" "3/1/2018" "4/1/2018" "9/1/2018"
这里是转换它们的第二种方法:
with(read.table(text = dates, sep = "/"), paste(V1, 1, V3, sep = "/"))
## [1] "1/1/2018" "2/1/2018" "3/1/2018" "4/1/2018" "9/1/2018"
答案 1 :(得分:1)
使用@G的基本思想。格洛腾迪克结合lubridate
:
ifelse(is.na(mdy(dates)), sub("/.*/", "/1/", dates), dates)
[1] "1/31/2018" "2/1/2018" "3/1/2018" "4/1/2018" "9/5/2018"
或将sub()
替换为strsplit()
:
day <- unlist(sapply(strsplit(dates, "/"), head, 1))
year <- unlist(sapply(strsplit(dates, "/"), tail, 1))
ifelse(is.na(mdy(dates)), paste(day, "1", year, sep = "/"), dates)