r-如何将数字和日期混合格式转换为单数格式



我有一个从excel导入的数据集中的日期列,该列混合了数字日期和dmY日期。此列当前的结构为字符。我想将其格式化为Ymd日期列。

例如

dates <- c(25678, 34758, 32474, 23443, "02/06/1999")
date_data <- data.frame(data = dates)
#hopeful end product
"1970-04-20" "1995-02-28" "1988-11-27" "1964-03-07", "1999-06-02"

所有这些日期都使用原点"0";1899-12-30";来自excel

我试过摆弄lubrigate的parse_date_time,但没有这样的运气。

这会检查日期格式并应用相应的转换。如果你遇到更多的格式,你将需要更多的其他If,每种格式一个If。

数据:

dates <- c(25678, 34758, 32474, 23443, "02/06/1999")
dates
[1] "25678"      "34758"      "32474"      "23443"      "02/06/1999"
as.vector(sapply( dates, function(x){
if( grepl("^[0-9]+$", x) ){
strftime(as.Date( as.integer(x), origin="1899-12-30" )) }
else{ strftime(as.POSIXlt(x, format="%d/%m/%Y")) } } ))

结果:

[1] "1970-04-20" "1995-02-28" "1988-11-27" "1964-03-07" "1999-06-02"
dates <- c(25678, 34758, 32474, 23443, "02/06/1999")
dplyr::if_else(stringr::str_length(dates) == 5, 
janitor::excel_numeric_to_date(as.numeric(dates)),  
lubridate::dmy(dates))
[1] "1970-04-20" "1995-02-28" "1988-11-27" "1964-03-07" "1999-06-02"
library(janitor)
convert_to_date(dates, character_fun = lubridate::dmy)
#> [1] "1970-04-20" "1995-02-28" "1988-11-27" "1964-03-07" "1999-06-02"

最新更新