【问题标题】:Converting Time to 'HMS" Character Format in R在 R 中将时间转换为“HMS”字符格式
【发布时间】:2019-03-15 19:50:42
【问题描述】:

我有一列日期时间,格式为“2000-11-21 10:01:01”、2000-11-21 00:02:01、2000-11-21 00:00:06。我想创建一个新列,将时间设置为 HMS 格式,例如,在上面的 3 个日期中,它将返回“HMS”、“MS”、“S”。我会尝试按照以下方式进行,但我想知道是否有更简单的方法:

ifelse(
  grepl("00:00:", datecolumn), "S", 
        ifelse(grepl("00:", datecolumn), "MS", "HMS")
)

输出:

 datecolumn                 HMS
2000-11-21 10:01:01         HMS
2000-11-21 00:02:01          MS
2000-11-21 00:00:06           S
2000-11-21 00:00:10           S
2000-11-21 00:10:06          MS
2000-11-21 00:00:07           S
2000-11-21 10:00:06         HMS

【问题讨论】:

  • 你能分享一个输出的例子吗? HMS,MS,S是什么意思
  • 添加了示例输出! HMS- 时分秒,MS- 分秒,S- 秒。

标签: r date time


【解决方案1】:

您可以像这样使用 lubridate 包和 paste

require(lubridate)
df$new_col <- paste(ifelse(hour(df$date) > 0, "H", ""), 
                    ifelse(minute(df$date) > 0, "M", ""), 
                    ifelse(second(df$date) > 0, "S", ""), sep = "")

【讨论】:

  • 啊,比我快5秒!
  • 这不会为2000-11-21 10:00:06 提供所需的结果
【解决方案2】:

将时间部分转换为data.table::ITime(“存储为一天中的整数秒数的时间类”),并使用适当的breakslabelscut 转换为:

d$HMS <- cut(data.table::as.ITime(d$datecolumn),
             breaks = c(0, 60 - 1, 60 * 60 - 1, Inf),
             labels = c("s", "ms", "hms"))
d
#                     datecolumn HMS
# 1          2000-11-21 10:01:01 hms
# 2          2000-11-21 00:02:01  ms
# 3          2000-11-21 00:00:06   s
# 4          2000-11-21 00:00:10   s
# 5          2000-11-21 00:10:06  ms
# 6          2000-11-21 00:00:07   s
# 7          2000-11-21 10:00:06 hms

【讨论】:

    【解决方案3】:

    来自dplyrcase_when() 函数可以提供嵌套ifelse 块的可读替代方案。 stringi 并不是真正需要的(grepl wld 工作正常),但我喜欢 stringi 函数名称的表达性(而 stringr 是 IMO 不必要的拐杖):

    library(stringi)
    library(tidyverse)
    
    read.csv(text="datecolumn,HMS
    2000-11-21 10:01:01,HMS
    2000-11-21 00:02:01,MS
    2000-11-21 00:00:06,S
    2000-11-21 00:00:10,S
    2000-11-21 00:10:06,MS
    2000-11-21 00:00:07,S
    2000-11-21 10:00:06,HMS", stringsAsFactors=FALSE) -> xdf
    

    注意这里的顺序很重要:

    mutate(xdf, computed_hms = case_when(
      stri_detect_regex(datecolumn, "00:00:[[:digit:]]{2}") ~ "S",
      stri_detect_regex(datecolumn, "00:[[:digit:]]{2}:[[:digit:]]{2}") ~ "MS",
      stri_detect_regex(datecolumn, "[[:digit:]]{2}:[[:digit:]]{2}:[[:digit:]]{2}") ~ "HMS"
      TRUE ~ NA_character_
    ))
    ##            datecolumn HMS computed_hms
    ## 1 2000-11-21 10:01:01 HMS          HMS
    ## 2 2000-11-21 00:02:01  MS           MS
    ## 3 2000-11-21 00:00:06   S            S
    ## 4 2000-11-21 00:00:10   S            S
    ## 5 2000-11-21 00:10:06  MS           MS
    ## 6 2000-11-21 00:00:07   S            S
    ## 7 2000-11-21 10:00:06 HMS          HMS
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-26
      • 1970-01-01
      • 2015-03-18
      • 2018-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多