将时间转换为R

时间:2018-10-10 20:10:13

标签: r date time

我有一列日期时间,格式为“ 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

3 个答案:

答案 0 :(得分:3)

您可以将lubridate软件包与SQL> with test (workorderid) as 2 (select 'AAB1' from dual union all 3 select 'AAB2' from dual union all 4 select 'AAB3' from dual 5 ) 6 select workorderid ||'-'|| column_value result 7 from test, 8 table(cast(multiset(select level from dual 9 connect by level <= 4 10 ) as sys.odcinumberlist)) 11 order by 1; RESULT ------------------------- AAB1-1 AAB1-2 AAB1-3 AAB1-4 AAB2-1 AAB2-2 AAB2-3 AAB2-4 AAB3-1 AAB3-2 AAB3-3 AAB3-4 12 rows selected. SQL> 一起使用,如下所示:

paste

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

case_when()中的dplyr函数可以为嵌套的ifelse块提供可读的替代方法。 stringi并不是真正需要的(grepl可以正常工作),但是我喜欢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