我需要解析日期并有类似“31/02/2018”的情况:
library(lubridate)
> dmy("31/02/2018", quiet = T)
[1] NA
这是有道理的,因为 2 月 31 日并不存在。有没有办法将字符串“31/02/2018”解析为例如2018-02-28 ?所以不是要获得 NA,而是要获得实际日期?
谢谢。
我们可以编写一个函数,假设您只有可能高于实际日期的日期,并且始终具有相同的格式。
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"
如果日期的格式不同,或者即使某些日期小于第一个日期,您也可以通过小的修改来调整日期。
使用 read.table 将各个部分分成 V1、V2 和 V3,然后创建月初的日期。减去一并加上日期。
d <- c("30/02/2008", "31/02/2008") # test data
with(read.table(text=d, sep ="/"), as.Date(sprintf("%d-%02d-01",V3,V2)) - 1 + V1)
## [1] "2008-03-01" "2008-03-02"