我有一个列的日期时间格式为'2000-11-21 10:01:01',2000-11-21 00:02:01',2000-11-21 00: 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发布于 2018-10-10 20:25:42
您可以像这样使用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 = "")发布于 2018-10-10 21:37:49
将时间部分转换为data.table::ITime (“存储为一天中的整数秒数的一天中的时间类”),并使用适当的breaks和labels对其进行cut。
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发布于 2018-10-10 20:56:11
来自case_when()的dplyr函数可以提供一个可读的替代嵌套ifelse块的方法。stringi并不是真正需要的(grepl工作得很好),但我喜欢stringi函数名的表现性( stringr是不必要的拐杖,海事组织):
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 HMShttps://stackoverflow.com/questions/52748046
复制相似问题