0

我需要解析日期并遇到像“31/02/2018”这样的案例:

library(lubridate)
> dmy("31/02/2018", quiet = T)
[1] NA

这是有道理的,因为 2 月 31 日不存在。有没有办法将字符串 "31/02/2018" 解析为例如 2018-02-28 ?所以不是得到一个NA,而是一个实际的日期?

谢谢。

4

1 回答 1

1

我们可以编写一个函数,假设您只有可能高于实际日期的日期,并且始终具有相同的格式。

library(lubridate)

get_correct_date <- function(example_date) {
  #Split vector on "/" and get 3 components (date, month, year)
  vecs <- as.numeric(strsplit(example_date, "\\/")[[1]])

  #Check number of days in that month
  last_day_of_month <-  days_in_month(vecs[2])

  #If the input date is higher than actual number of days in that month
  #replace it with last day of that month
  if (vecs[1] > last_day_of_month)
    vecs[1] <- last_day_of_month

  #Paste the date components together to get new modified date
  dmy(paste0(vecs, collapse = "/"))
}


get_correct_date("31/02/2018")
#[1] "2018-02-28"

get_correct_date("31/04/2018")
#[1] "2018-04-30"

get_correct_date("31/05/2018")
#[1] "2018-05-31"

如果日期格式不同,或者即使某些日期小于第一个日期,只需稍作修改,您就可以调整日期。

于 2018-11-09T13:05:15.180 回答