本文介绍了将时间对象转换为 R 中的分类(早上、下午、晚上、晚上)变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在时间数据框中有这个向量,格式为小时:分钟,我想转换为一天中的分类时间:
I have this vector in a data frame of times in the format of hours:minutes that I want converted to categorical times of day:
time <- c("15:03", "08:01", "11:59", "23:47", "14:20")
df$time <- format(strptime(df$time, tz = "" , format = "%H: %M"), format = "%H: %M")
df <- data.frame(time)
我想我会考虑早上 5 点到 11 点,下午 11 点到 16 点,晚上 16 点到 19 点,以及除此之外的任何事情,直到 5 晚.原始数据的时间格式为小时:分钟,带 strptime().
I suppose I would consider 5-11 the morning, 11-16 the afternoon, 16-19 evening, and anything beyond that and up until 5 night. The original data is in time format as hours:minutes with strptime().
我在论坛上发现了一些类似的问题,但我似乎无法调整代码来处理我的数据.
I found some similar problems on the forum but I couldn't seem to tweak the code to work on my data.
推荐答案
time <- as.POSIXct(strptime(c("15:03", "08:01", "11:59", "23:47", "14:20"),"%H:%M"),"UTC")
x=as.POSIXct(strptime(c("050000","105959","110000","155959","160000",
"185959"),"%H%M%S"),"UTC")
library(tidyverse)
case_when(
between(time,x[1],x[2]) ~"morning",
between(time,x[3],x[4]) ~"afternoon",
between(time,x[5],x[6]) ~"evening",
TRUE ~"night")
[1] "afternoon" "morning" "afternoon" "night" "afternoon"
使用基础 R:
time <- as.POSIXct(strptime(c("15:03", "08:01", "11:59", "23:47", "14:20"),"%H:%M"),"UTC")
x=as.POSIXct(strptime(c("000000","050000","110000","160000","190000","235959"),
"%H%M%S"),"UTC")
labs=c("night","morning","afternoon","evening","night")
labs[findInterval(time,x)]
[1] "afternoon" "morning" "afternoon" "night" "afternoon"
这篇关于将时间对象转换为 R 中的分类(早上、下午、晚上、晚上)变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!