将日期转换为时间间隔

时间:2017-12-06 14:05:04

标签: r

我的data.frame中有一个格式为日期("2006-03-09 17:00:00")的列,我想要一个新列,它会为我提供范围,例如" morning","下午","晚上"。我正在尝试以下方面但没有成功:

mydf <- mydf %>%
        mutate (dateInterval = ifelse (data < "13:00", "morning",
                               ifelse (data > "18:00", "evening", "afternoon")))

2 个答案:

答案 0 :(得分:1)

## Building your datetime data
datetime <- c("2006-03-09 17:00:00", "2006-03-09 19:00:00", "2006-03-09 10:00:00", "2006-03-09 22:00:00")

hour <- as.integer(substr(datetime, 12, 13))
df <- data.frame(datetime=datetime, hour=hour, dateInterval=cut(hour, c(0, 7, 10, 12, 18, 24), labels=c("night", "morning", "noon", "afternoon", "evening")))

df
#             datetime   hour  dateInterval
#1 2006-03-09 17:00:00    17      afternoon
#2 2006-03-09 19:00:00    19        evening
#3 2006-03-09 10:00:00    10        morning
#4 2006-03-09 22:00:00    22        evening

答案 1 :(得分:0)

您尚未共享数据,因此很难制作临时解决方案。

步骤如下: 1)确保您的日期在POSIXct班级

mydf$timestamp <- as.POSIXct(paste(mydf$timestamp, mydf$timestamp), format="%Y-%m-%d %H:%M:%S")

2)从此Date&amp; Time对象中提取Hour组件

mydf$hour <- format(strptime(as.character(mydf$timestamp), "%H:%M:%S"), "%H:%M:%S")

3)创建一个包含time_slot信息

的表格
description <- c("Morning", "Day", "Evening", "Night")
from <- as.character(c("07:00:00", "10:30:00", "17:30:00", "20:30:00"))  
to <- as.character(c("10:29:59", "17:29:59", "20:29:59", "06:59:59"))  
context_table <- data.frame(description, from, to)

4)请确保context_table$fromcontext_table$tocharacter类型,以便与mydf$hour进行比较

context_table$from <- as.character(context_table$from)
context_table$to <- as.character(context_table$to)

5)将context_table$descriptionmydf

中的每条记录相关联
mydf$time_slot <- NULL
for (i in 1:(dim(context_table)[1]-1)){
        mydf[mydf$hour_crash >= context_table$from[i] & mydf$hour_crash <= context_table$to[i], "time_slot"] <- context_table[i, "description"]
}
mydf[is.na(mydf$time_slot), "time_slot"] <- context_table[dim(context_table), "description"]

由于时钟在[00:00:00; 23:59:59],有必要进行第5点的解决方法。