我的data.frame
中有一个格式为日期("2006-03-09 17:00:00"
)的列,我想要一个新列,它会为我提供范围,例如" morning","下午","晚上"。我正在尝试以下方面但没有成功:
mydf <- mydf %>%
mutate (dateInterval = ifelse (data < "13:00", "morning",
ifelse (data > "18:00", "evening", "afternoon")))
答案 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$from
和context_table$to
为character
类型,以便与mydf$hour
进行比较
context_table$from <- as.character(context_table$from)
context_table$to <- as.character(context_table$to)
5)将context_table$description
与mydf
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点的解决方法。