如何在r中排列到日期的false(不存在)字符列?(类似于将字符列转换为r中的日期)


ymd("2011-11-31") 
All formats failed to parse. No formats found.[1] NA

2011-11有30天没有31天,所以ymd得到了失败的状态。我的数据在这样的日期列中有一些错误的日期,我想学习一种优雅的处理方法。是否有任何包或函数的数据会变成这样;2011-12-01";?

我不知道,但你可以定义自己的函数来处理它。
这里我取日期的年-月部分,然后加上天数,如果需要的话,让它进入下一个月(甚至一年(。

# two invalid, one valid date
x <- c("2011-11-31", "2000-04-31", "2010-01-10", "2011-12-32")
parse_bad_dates <- function(x) {
as.Date(paste(substr(x, 1, 7), "1"), format="%Y-%m %d") +
as.numeric(substr(x, 9, 10)) - 1
}
parse_bad_dates(x)
#[1] "2011-12-01" "2000-05-01" "2010-01-10" "2012-01-01"

这里的答案类似,但也适用于滚动月份和年份

library(lubridate)
d <- c("2011-11-31",'2011-13-04','2011-12-32')
parse_false_date <- function(d) {
x <- strcapture("(\d{4})-(\d{2})-(\d{2})", d, 
data.frame(y=integer(),m=integer(),d=integer()))
make_date(x$y)+months(x$m-1)+days(x$d-1)
}
parse_false_date(d)
#> [1] "2011-12-01" "2012-01-04" "2012-01-01"

最新更新