Kuo-Hsien Chang
Kuo-Hsien Chang

Reputation: 935

R: calculate 1-hour average in an irregular 1-min time series

I am trying to use R to calculate 30-min and 1-hour average in an irregular 1-min time series.

Here is the data set looks like:

Sensor_reading      Time

  -0.28     1-25-16 15:00
  -0.27     1-25-16 15:01
  -0.27     1-25-16 15:02
  -0.26     1-25-16 15:03
  -0.25     1-25-16 15:04
  -0.26     1-25-16 15:05
  -0.28     1-25-16 15:06
  -0.28     1-25-16 15:07
  -0.27     1-25-16 15:08
  -0.30     1-25-16 15:12
  -0.31     1-25-16 15:13
  -0.30     1-25-16 15:14
  -0.30     1-25-16 15:15
  -0.31     1-25-16 15:16
  -0.31     1-25-16 15:17
  -0.31     1-25-16 15:18
  -0.31     1-25-16 15:19
  -0.30     1-25-16 15:20
  -0.27     1-25-16 16:00
  -0.28     1-25-16 16:01
  -0.27     1-25-16 16:02
  -0.26     1-25-16 16:03
  -0.26     1-25-16 16:04
  -0.26     1-25-16 16:06

How can I use R to generate an average dataset looks like this:

   30mins-output      Time
  -0.24     1-25-16 16:00
  -0.26     1-25-16 16:30
  -0.22     1-25-16 17:00
  -0.25     1-25-16 17:30


   1hour-output      Time
  -0.25     1-25-16 16:00
  -0.23     1-25-16 17:00

Upvotes: 2

Views: 827

Answers (1)

Zakkery
Zakkery

Reputation: 420

You can use cut function and then dplyr summarize:

data$Time <- strptime(data$Time, "%m-%d-%y %H:%M")
data$group <- cut(data$Time, breaks="30 min")
data %>% group_by(data$group) %>% summarize(30mins_output = mean(data$Sensor_reading))

Similarly for an hour you can do:

data$group <- cut(data$Time, breaks="hour")

Upvotes: 2

Related Questions