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)
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.
Using base R:
This one is similar to @Onyambu, only using
plyr
'smapvalues()
andlubridate
'shour()
:Using some
regex
andifelse
I was able to use an
ifelse
statement to make the categories. I changed thestrptime
toas.POSIXct
and only kept the hour to make the groups. In the df there are 3 columns representing the original time, just the hour, and then the group. You can change it to be a factor withas.factor
if the category needs to be a factor.I think this gets it done, I'm not sure how to get cut to acept duplicate labels, but maybe someone else will. The key was to use
chron::times()
to create a chronological object instead of a datetime object.update: