0

Working on Time differences and want to create time slots based on different times in my dataframe. For example I do have separate column in my data frame which contains seconds. What I want to do is by checking these seconds whether it is falling in any one of the category i.e time slots.

timediff(in Sec)      Waiting_slots
14589                    >= 4 hours
11580                    2 - 4 hours
11940                    2 - 4 hours

 date 
 2018-01-19 15:17:48 UTC--2018-01-19 19:20:57 UTC
 2016-06-26 22:55:00 UTC--2016-06-27 02:08:00 UTC
 2016-05-02 07:47:00 UTC--2016-05-02 11:06:00 UTC

etc so, waiting slots is like <=2 hour, 2 - 4 hours, >4 hours I have to create waiting _slots like this but failed to achieve this because I dont know how to do it time intervals for 2 - 4 hours. I have tried this method,

# timed <- c(2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,2.9,3.0,3.1,3.2,3.3,3.4,3.5,3.6,3.7,3.8,3.9)
# AE_subset <- mutate(AE_subset, waiting_slots = ifelse(timediff < 2.0,"Less than 2 hours",
#                                                       ifelse(timediff  %in% timed,"Between 2 - 4 hours",
#                                                              ifelse(timediff > 4.0,"More than 4 hours","check"))))
# AE_subset <- AE_subset %>% mutate(waiting_slots = replace(waiting_hours,waiting_hours== "check","Between 2 - 4 hours"))

I have used duration from Lubridate to convert seconds to hours format.

> duration(timediff = 14589)
[1] "14589s (~4.05 hours)"

    ae <- ae %>% mutate(wait_slots = cut(ae$time_interval, breaks = c(7199,14400,121918,Inf),labels = c("Less than 2 hours","Between 2 to 4 hours","More than 4 hours")))

Using the above method gives me wrong grouping. can anyone help me to solve this please!!!

Sharmi
  • 43
  • 9

2 Answers2

0

It would be helpful if you would provide a min example of your data in hand. Maybe this can help you?

# generate data with random timestamps
timeStart <- sort(as.POSIXct(sample(1000:10000,20),origin="1970-01-01"))
timeEnd <- timeStart + as.difftime(seq(0,10,length.out = 20),units="hours")
data <- data.frame(start = timeStart, end = timeEnd)

# function for time categorisation
timeCategory <- function(t0,t1){
  diffTime <- difftime(t1,t0,units = "hours")
  if(diffTime < 2){
    return(1)
  }else if(2<= diffTime && diffTime < 4){
    return(2)
  }else{
    return(3)
  }
}

#apply function to data
timeCat <- apply(data,1,function(t)timeCategory(t[1],t[2]))
timeCat
HolgerBarlt
  • 277
  • 1
  • 16
0

Here is the command I have used to get the output:

 DF<- DF %>% mutate(waiting_hours = cut(DF$ELAPSED_MINS_ARRIVAL_TO_DEPARTURE, breaks = c(0,119,239,2031),labels = c("Less than 2 hours","2 to 4 hours","More than 4 hours"),include.lowest = TRUE))
Sharmi
  • 43
  • 9