【问题标题】:How to split column containing date and time when null values are present in R?当 R 中存在空值时,如何拆分包含日期和时间的列?
【发布时间】:2021-10-12 19:32:03
【问题描述】:

我有一列包含这样的数据

df <- data.frame(request_time = c("2020-12-31 13:05:00", NULL, "2020-11-14 02:04:01")

我想拆分 request_time 列以仅提取日期。希望有一个名为 request_date 的新列。

我正在尝试执行以下操作:

df$request_date <- as.Date(df$request_time) 

但这会返回一个错误,指出“字符串不是标准的明确格式”我假设由于存在 NULLS 而出现日期。我怎样才能克服这个问题?

【问题讨论】:

  • 你确定你的值是NULL吗?因为您的向量中不能有 NULL 值。如果您运行示例代码(在添加缺少的右括号之后),您会看到它只有两行。您的意思是 NA 值而不是 NULL 吗?如果您包含一个简单的reproducible example 以及可用于测试和验证可能的解决方案的示例输入,那么为您提供帮助会更容易。

标签: r datetime


【解决方案1】:

我们可以将as_date 函数与来自lubridate 包的ymd 一起使用:

library(dplyr)
library(lubridate)
df %>% 
  mutate(request_time = ymd(as_date(request_time)))

输出:

  request_time
1   2020-12-31
2   2020-11-14

library(tidyr)
df %>% 
  separate(request_time, c("date", "time"), sep=" ", remove = FALSE)
        request_time       date     time
1 2020-12-31 13:05:00 2020-12-31 13:05:00
2 2020-11-14 02:04:01 2020-11-14 02:04:01

【讨论】:

    【解决方案2】:

    只需使用str_extract提取日期:

    library(stringr)
    library(dplyr)
    f %>%
      mutate(request_time = str_extract(request_time, "[0-9-]+"))
      request_time
    1   2020-12-31
    2   2020-11-14
    

    base R:

    f$request_time <- str_extract(f$request_time, "[0-9-]+")
    

    【讨论】:

    • str_extract 不是基本 R 函数
    【解决方案3】:

    NULL 部分不清楚。如果是字符串"NULL",则as.Date 应该返回NA。否则,NULL 不能这样存在。可能是list 列(不清楚)

    df$request_time <- as.Date(df$request_time)
    

    -输出

    df$request_time
    [1] "2020-12-31" NA           "2020-11-14"
    

    数据

    df <- data.frame(request_time = c("2020-12-31 13:05:00", "NULL", "2020-11-14 02:04:01"))
    

    【讨论】:

      猜你喜欢
      • 2019-09-21
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      • 1970-01-01
      • 2021-03-24
      • 2021-10-10
      • 1970-01-01
      • 2020-10-18
      相关资源
      最近更新 更多