【问题标题】:Parsing dates with different formats using lubridate使用 lubridate 解析不同格式的日期
【发布时间】:2021-01-06 13:16:54
【问题描述】:

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

我已经在Parsing dates with different formatsParsing 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" 的日期返回 NA 并且该列的类显示为未知。

我尝试过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)

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

谢谢

【问题讨论】:

  • 1/05/1990 的格式是 %d/%m/%Y 还是月份优先?
  • @RuiBarradas 这是第一天格式
  • 我下面的回答能回答这个问题吗?它有一个参数format 用于可能的格式。

标签: r lubridate


【解决方案1】:

以下函数将尝试在其参数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"

【讨论】:

  • 抱歉延迟回复 - 我刚刚有时间再看一遍。您的代码有效,但让我进入了一个类似的位置,其中 DATE 被归类为&lt;dttm&gt;。我试图将其归类为&lt;date&gt;,这样当我使用ggplot 时,我可以使用scale_x_date() 之类的代码。我希望在读取 CSV 文件时有一种更简单的方法可以解析 DATE 列?感谢您的帮助
  • @cromj006 Class dttm 是一个日期时间类,例如,参见this SO post
  • 感谢您的澄清和帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-11
  • 1970-01-01
  • 2022-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多