3

My dataset class has "time" feature. This feature belongs to character class. I try to show the frequency of pick up per different time slot.For this reason, I used "cut" function as below:

FreqPickupTime <- cut(dt$time, breaks = "hour")

But, I occur with the below error.

Error in cut.default(dt$time, breaks = "hour") :'x' must be numeric.

is there any solution to use this cut function for character features.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • 1
    `cut()` won't work on character values. Are you string dates in the column? Then you'll need to convert to a proper date time value. See `?strptime`. The `cut()` function has special properties for date time (POSIXt) values. It would be better if you included a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input data so we know exactly what your data looks like. – MrFlick Apr 07 '17 at 15:13

1 Answers1

2

As MrFlick says, cut() won't cut it for characters.

Say df$time looks something like: 16:42, 12:32, 03:20...

For example:

time <- paste0(round(runif(1000, 0, 23), digits = 0), ':', round(runif(1000, 1, 59), digits = 0))

You could simply do:

table(substr(time, 1, regexpr(':', time)-1))
Jérôme
  • 1,254
  • 2
  • 20
  • 25
Majo
  • 176
  • 1
  • 9
  • thanks for the sample but it does not work on my data set. My data is like "00:28:14". I want to use subset data based on time slot 00:00- 6:00, and 6:00- 12:00 , and 12:00 - 5:00 and ... – Behzad Nazarbakhsh Apr 07 '17 at 21:23
  • All right, did you remember to change the variable name in the `table()` call to `table(substr(df$time, 1, regexpr(':', df$time)-1))'`? Maybe, try to post what `typeof(df$time)`returns here? The thing is, this code should work even if your data is formated the way you say. – Majo Apr 08 '17 at 15:51
  • use `df$time <- as.POSIXct(df$time)` and then `cut` will work. – dash2 Apr 28 '21 at 11:40