使用 lubridate 解析不同格式的日期

Parsing dates with different formats using lubridate

我正在从 csv 文件导入数据,其中日期列包含以不同格式记录的日期。我希望解析该列,使其具有 class date 并且所有日期的格式都相同(即 %d-%m-%Y)。我希望使用 lubridate,因为我有一些使用它的经验,并希望更好地使用它。

我在这里寻找答案 Parsing dates with different formats and here Parsing dates in multiple formats in R using lubridate 但我发现答案不完整。

通常,当我导入 csv 数据时,我会像这样更改 col_types

potatoes <- read_csv("data/potato_prices.csv",
           col_types = cols(
           DATE = col_date(format = "%Y-%m-%d"), 
           'M04003DE00BERM372NNBR' = col_double())) %>% 
           rename("Price" = "M04003DE00BERM372NNBR")

但是因为我的 DATE 列包含不同格式的日期,所以日期格式不像 "%Y-%m-%d" return 和 NA 并且列的 class 显示为未知。

我已经尝试 col_guess,而不是用 col_date 指定确切的日期格式,然后用以下代码改变 DATE 列,但它没有像我想要的那样工作。

potatoes <- read_csv("data/potato_prices.csv",
                      col_types = cols(
                      DATE = col_guess(),
                      'M04003DE00BERM372NNBR' = col_double())) 

potatoes <- potatoes %>% 
  mutate(DATE = parse_date_time(DATE, orders = c("Ymd", "dmY"))) %>%
  rename("Price" = "M04003DE00BERM372NNBR")

这是我的数据如何以 csv 格式显示在 excel 中的示例

DATE <- c("1879-01-01", "1879-02-01", "1879-03-01", "1879-04-01", "1/05/1990", "1/06/1990", "1/07/1990", "1/08/1990", "1/09/1990", "1/10/1990")
Price <- c("23", "17.9", "17.8", "18", "20", "22", "20", "19", "17.2", "15")

spuds <- data.frame(DATE, Price)

我希望有两列的标题;日期为 class col_date,价格为 class col_double。然后我将使用 ggplot 创建绘图,我认为如果我的 DATE 列在 class 日期中,那将是最简单的。

谢谢

以下函数将尝试在其参数 format 中传递的几种日期格式。它使用 lubridate 函数 guess_formats 以获得基于该参数的可能格式。

as_Date <- function(x, format = c("ymd", "dmy", "mdy")){
  fmt <- lubridate::guess_formats(x, format)
  fmt <- unique(fmt)
  y <- as.Date(x, format = fmt[1])
  for(i in seq_along(fmt)[-1]){
    na <- is.na(y)
    if(!any(na)) break
    y[na] <- as.Date(x[na], format = fmt[i])
  }
  y
}

formats <- c("ymd", "dmy")
as_Date(spuds$DATE, formats)
#[1] "1879-01-01" "1879-02-01" "1879-03-01" "1879-04-01"
#[5] "1990-05-01" "1990-06-01" "1990-07-01" "1990-08-01"
#[9] "1990-09-01" "1990-10-01"