Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: calculate average over a specific time window in a time series data frame

Tags:

r

My dataset is a bit noisy at 1-min interval. So, I'd like to get an average value every hour from 25 min to 35 min to stand for that hour at 30 min.

For example, an average average at: 00:30 (average from 00:25 to 00:35), 01:30 (average from 01:25 to 01:35), 02:30 (average from 02:25 to 02:35), etc.

Can you good way to do this in R?

Here is my dataset:

  set.seed(1)
  DateTime <- seq(as.POSIXct("2010/1/1 00:00"), as.POSIXct("2010/1/5 00:00"), "min")
  value <- rnorm(n=length(DateTime), mean=100, sd=1)
  df <- data.frame(DateTime, value)

Thanks a lot.

like image 981
Kuo-Hsien Chang Avatar asked Mar 13 '23 16:03

Kuo-Hsien Chang


1 Answers

Here's one way

library(dplyr)
df %>% 
  filter(between(as.numeric(format(DateTime, "%M")), 25, 35)) %>% 
  group_by(hour=format(DateTime, "%Y-%m-%d %H")) %>%
  summarise(value=mean(value))
like image 81
lukeA Avatar answered Mar 15 '23 14:03

lukeA