有没有办法将几个数字字符替换为 R 中的日期?

Is there a way to replace only a few numeric character to a date in R?

所以我在 R 中使用了这段代码:

excel_numeric_to_date(as.numeric(as.character(sheet1$col4)), date_system = "modern")

将所有数字字符替换为 excel 中的日期,效果很好!但是我现在有一个 sheet,其中一些日期显示为日期,一些显示为数字。例如:

现在当我使用相同的代码时,它更改了数字但删除了日期。有人知道解决这个问题的方法吗?

从 akrun 的 answer here 获得灵感,您可以使用 coalesce 合并 janitorexcel_numeric_to_date 和 [=16= 的 dmy 的结果].

如果最终更适合您的实际数据,您可以使用 mdy

library(janitor)
library(dplyr)
library(lubridate)
coalesce(excel_numeric_to_date(as.numeric(sheet1$col4)),
         dmy(sheet1$col4))
#[1] "2020-01-01" "2006-06-12" "2007-06-06" "2019-02-02"

示例数据:

sheet1 <- structure(list(col4 = c("01/01/2020", "38880", "39239", "02/02/2019"
)), class = "data.frame", row.names = c(NA, -4L))