How to bin a time column in r

Hi,
I have a column in a data frame with different times (as e.g.15:20:00). There is no date in the column. I am trying to bin this into 2 hour intervals. Does anyone know how I can do this?

Thanks!

You can find the hms useful to handle time values

Something like

library(hms)
library(dplyr)
#> 
#> Attachement du package : 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

# build df with hms value
tab <- expand.grid(H = hms(hours = 1:10), M = hms(minutes = (0:5)*10)) %>%
  transmute(time = as_hms(H + M), value = rnorm(length(time))) %>%
  as_tibble()

# use hms function to work with time object
tab %>%
  mutate(two_hours = trunc_hms(time, 60*60*2)) %>%
  group_by(two_hours) %>%
  summarise(value = sum(value))
#> # A tibble: 6 x 2
#>   two_hours  value
#>   <time>     <dbl>
#> 1 00:00     -1.31 
#> 2 02:00     -3.75 
#> 3 04:00      1.37 
#> 4 06:00      4.53 
#> 5 08:00     -0.882
#> 6 10:00      1.71

Created on 2019-11-15 by the reprex package (v0.3.0)

Otherwise, you can also extract character and then group by hours I guess

There are also specialized packages to perform time aggregation, like tsibble and tibbletime

library(hms)
library(dplyr)
library(tibbletime)

tab <- expand.grid(H = hms(hours = 1:10), M = hms(minutes = (0:5)*10)) %>%
    transmute(time = as_hms(H + M), value = rnorm(length(time))) %>%
    as_tibble()

tab %>%
    arrange(time) %>% 
    as_tbl_time(index = time) %>% 
    collapse_by("2 hours", side = "start", clean = TRUE) %>%
    group_by(time) %>% 
    summarise(value = sum(value))
#> # A time tibble: 6 x 2
#> # Index: time
#>   time    value
#>   <time>  <dbl>
#> 1 00:00  -5.11 
#> 2 02:00   2.78 
#> 3 04:00  -2.88 
#> 4 06:00  -1.47 
#> 5 08:00   2.36 
#> 6 10:00   0.793
1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.