Aggregate data by equally spaced time intervals in R -
my dataset this
section time x s3 9:35 2 s4 9:35 2 s1 9:36 1 s2 10:01 1 s8 11:00 2 so, want group data section wise on hourly interval , sum x values lies in interval
my expected output is
sec time x s1 9:00-10:00 1 s2 9:00-10:00 0 s3 9:00-10:00 2 s4 9:00-10:00 2 s8 9:00-10:00 0 s1 10.00-11.00 0 s2 10.00-11.00 1 s3 10.00-11.00 0 s4 10.00-11.00 0 s8 10.00-11.00 1 i tried post in stack overflow, getting following error query. here x frame
data.frame(value = tapply(cbind(x$x), list(sec= x$section,cut(x$time, breaks="1 hour")), sum)) error in cut.default(x$time, breaks = "1 hour") : 'x' must numeric i not sure if right or wrong. never worked time data in r. on how can achieve great help.
i think problem lies in fact time column in character format ?
anyway, here quick , dirty approach using dplyr :
library(dplyr) x <- data.frame(section = c("s3", "s4", "s1", "s2", "s8", "s1", "s2", "s3"), time = c("9:35", "9:35", "9:36", "10:01", "11:00", "9:45", "10:05", "10:05"), x = c(2, 2, 1, 1, 2, 6, 2, 4), stringsasfactors = false) x %>% rowwise %>% mutate(aux = as.numeric(strsplit(time, ":")[[1]][1]), time = paste0(aux, ":00-", aux+1, ":00")) %>% select(-aux, -time) %>% ungroup %>% group_by(time, section) %>% summarise(x = sum(x)) %>% ungroup
Comments
Post a Comment