Hardik Gupta
Hardik Gupta

Reputation: 4790

Cut timestamp into numeric slots in R

I have timestamp column, having data in the form 2016-01-01 00:41:23

I want to convert this data into 12 slots each of 2hrs from the entire dataset. The data is of not importance, only the time needs to be considered.

00:00:00 - 01:59:59 - slot1
02:00:00 - 03:59:59 - slot2
.......
22:00:00 - 23:59:59 - slot12

How can I achieve this in R?

x <- c("01:59:59", "03:59:59", "05:59:59",
   "07:59:59", "09:59:59", "11:59:59",
   "13:59:59", "15:59:59", "17:59:59",
   "19:59:59", "21:59:59", "23:59:59")

cut(pickup_time, breaks = x)

Above code gives error: : 'x' must be numeric

Upvotes: 2

Views: 451

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388962

Considering your dataframe as df we can use cut with breaks of 2 hours.

df$slotnumber <- cut(strptime(df$x, "%H:%M:%S"), breaks = "2 hours", 
                                                labels = paste0("slot", 1:12))

#      x       slotnumber
#1  01:59:59      slot1
#2  03:59:59      slot2
#3  05:59:59      slot3
#4  07:59:59      slot4
#5  09:59:59      slot5
#6  11:59:59      slot6
#7  13:59:59      slot7
#8  15:59:59      slot8
#9  17:59:59      slot9
#10 19:59:59     slot10
#11 21:59:59     slot11
#12 23:59:59     slot12

data

df <- data.frame(x)

Upvotes: 2

Related Questions