r - Aggregating time on hourly basis and counting it -


i have following dataframe in r.

 date                    car_no  2016-12-24 19:35:00       abc  2016-12-24 19:55:00       def  2016-12-24 20:15:00       rty  2016-12-24 20:35:00       wer  2016-12-24 21:34:00       der  2016-12-24 00:23:00       abc  2016-12-24 00:22:00       ert  2016-12-24 11:45:00       rty  2016-12-24 13:09:00       rty 

date format "posixct" "posixt"

i want count hourly movement of car traffic. 12-1,1-2,2-3,3-4 , on

currently approach following

df$time <- ymd_hms(df$date)  df$hours <- hour(df$time)  df$minutes <- minute(df$time)  df$time <- as.numeric(paste(df$hours,df$minutes,sep=".")) 

and after apply ifelse loop divide in hourly time slots,but think long , tedious way it. there easy approach in r.

my desired dataframe be

 time_slots      car_traffic_count    00-01               2    01-02               0    02-03               0     .                   .     .    19-20               2    20-21               2    21-22               1     .     .     . 

simplest use starting hour indicate time interval:

# sample data df = data.frame(time = sys.time()+seq(1,10)*10000, runif(10) )  # summarize library(dplyr) df$hour = factor(as.numeric(format(df$time,"%h")), levels = seq(0,24)) df = df %>%        group_by(hour) %>%        summarize(count=n()) %>%        complete(hour, fill = list(count = 0)) 

output:

# tibble: 24 x 2      hour count    <fctr> <dbl>  1      0     0  2      1     1  3      2     0  4      3     0  5      4     1  6      5     0  7      6     1  8      7     0  9      8     0 10      9     1 # ... 14 more rows 

you can optionally add:

df$formatted = paste0(as.character(df$hour),"-",as.numeric(as.character(df$hour))+1) 

at end desired format. hope helps!


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -