如何导入 excel 电子表格,其中的日期列包含文本和数字日期格式?例如,(“3-Dec-19”、“2019-05-04”、“43787”

How do I import an excel spreadsheet where there is a date column that has text and numerical date formats? eg, ("3-Dec-19", "2019-05-04", "43787"

如果我有多个包含不同格式的日期列的电子表格,如果某些行具有数字格式,是否可以转换日期?

如果我将列作为字符导入,我仍然需要转换为日期。我相信 parse_date_time 会解决任何接受数字格式的问题。

下面将转换前两个而不是数字版本。我不认为这个函数有数字函数。 是否有可以同时处理文本和数字日期的函数?

x<- c("2019-12-05","8-Dec-19","43787")
lubridate::parse_date_time(x, c("ymd", "d-b-y"))

它有点笨拙,但是您可以使用 janitor::excel_numeric_to_date() 对任何数字值进行第二次遍历,并且无法通过 parse_date_time 解析...(如果您要经常使用它,您可以编写一个包装函数 - 您可能还想抑制来自 parse_date_timeas.numeric ...)

的警告消息
x <- c("2019-12-05","8-Dec-19","43787")
y <- lubridate::parse_date_time(x, c("ymd", "d-b-y"))
exceld <- is.na(y) & !is.na(as.numeric(x))
y[exceld] <- janitor::excel_numeric_to_date(as.numeric(x[exceld]))

也许有更好的方法,但我能够使用 tryFormats 创建一个函数来处理日期格式的数字和文本版本。

dfix(c("2019-12-05","8-Dec-19","43787"))

[1] "2019-12-05" "2019-12-08" "2019-11-18"

dfix<-function(x1){
  dout<-c()
  for (x in x1){
    if(grepl('\d{5}',x)){ #Check for numeric date (5 digits)
      n<-as.numeric(x)
      d<-as.Date(n, origin = "1899-12-30")
    }
    else if (grepl('-',x)){ # TryFormats for dates with "-" 
      d<-as.Date(x,tryFormats = c("%Y-%m-%d","%d-%b-%y"))
    }
    dout<-c(dout,d)
  }
  
  return (as.Date(dout,origin = '1970-01-01'))
}