我需要从用户完成的 Excel 表单中转换日期字符串,这些表单可以采用多种格式,包括将日期作为 Excel 整数(我知道这本来可以被阻止,但事实并非如此)。我想将以下内容转换为日期:
excel_dates <- tibble(string_date = c("2012-01-01", "42123"))
我尝试过:
excel_dates |>
mutate(
date = ifelse(
is.na(suppressWarnings(as.numeric(string_date))),
as.Date(string_date),
as.Date(as.numeric(string_date), origin = "1899-12-30")
)
)
但这不会产生日期(显然是
ifelse()
设计)。
我也尝试过使用
if_else()
但失败了,因为它无法检查 TRUE
和 FALSE
结果的数据类型是否相同 - 因为其中一个失败了。
我正在寻找一个相对简单的解决方案。
这比我想要的要长并引发警告(因为我猜它会在每个条目上尝试
excel_numeric_to_date()
?),但确实会产生正确的输出:
library(dplyr)
is_num <- function(x) stringr::str_detect(x, "^[0-9]+$")
excel_dates |>
mutate(date = case_when(is_num(string_date)
~ janitor::excel_numeric_to_date(as.numeric(string_date)),
TRUE ~ as.Date(string_date)))