tidyverse / hms

A simple class for storing time-of-day values
https://hms.tidyverse.org/
Other
138 stars 25 forks source link

cut() method for `hms` class #99

Open vgherard opened 3 years ago

vgherard commented 3 years ago

Hi,

in some analyses I frequently need to cut() over an hms variable and I was wondering if you could find useful having a cut.hms method added to the package. I have written my own function and I can provide a PR if you are interested.

Here's the kind of output I'm producing for some basic cases:

library(hms)

# Basic example
x <- parse_hm(
  c("06:59", "07:00", "07:15", "07:30", "07:45", "08:00", "08:01")
  )
breaks <- parse_hm( c("07:00", "07:30", "08:00") )
cut(x, breaks)
#> [1] <NA>           <NA>           (07:00, 07:30] (07:00, 07:30] (07:30, 08:00]
#> [6] (07:30, 08:00] <NA>          
#> Levels: (07:00, 07:30] (07:30, 08:00]

# [a,b) intervals
cut(x, breaks, right = FALSE)
#> [1] <NA>           [07:00, 07:30) [07:00, 07:30) [07:30, 08:00) [07:30, 08:00)
#> [6] <NA>           <NA>          
#> Levels: [07:00, 07:30) [07:30, 08:00)

# Custom labels
labels <- c("A", "B")
cut(x, breaks, labels)
#> [1] <NA> <NA> A    A    B    B    <NA>
#> Levels: A B

# Number of digits in the automatic labels is inferred from 'breaks'
x <- as_hms( c("07:00:01", "07:00:45", "07:01:12", "07:01:29") )
breaks <- as_hms( c("07:00:00", "07:00:30", "07:01:00", "07:01:30") )
cut(x, breaks)
#> [1] (07:00:00, 07:00:30] (07:00:30, 07:01:00] (07:01:00, 07:01:30]
#> [4] (07:01:00, 07:01:30]
#> Levels: (07:00:00, 07:00:30] (07:00:30, 07:01:00] (07:01:00, 07:01:30]
x <- hms( hours = c(3, 15, 19) )
breaks <- hms( hours = c(0, 12, 24) )
cut(x, breaks)
#> [1] (00, 12] (12, 24] (12, 24]
#> Levels: (00, 12] (12, 24]

Bests,

Valerio

Created on 2021-04-16 by the reprex package (v1.0.0)