Reputation: 438
I have a time series data with 3 columns with Dates,energy values and Station names. I want to obtain the hourly average of the energy values separately for each station.
My data looks like this
df
Datetime Energy Station
1 2016-01-01 07:19:00 743.0253 Ajmer
2 2016-01-01 07:20:00 765.7225 Ajmer
3 2016-01-01 07:21:00 788.1493 Ajmer
4 2016-01-01 08:20:00 834.7815 Ajmer
5 2016-01-01 08:21:00 857.3012 Ajmer
6 2016-01-31 16:58:00 3427.098 Kotada
7 2016-01-31 16:59:00 3397.591 Kotada
8 2016-01-31 17:00:00 3344.149 Kotada
9 2016-01-31 17:01:00 3270.803 Kotada
Expected Output:
Datetime Energy Station
1. 2016-01-01 07:00:00 765.6324 Ajmer
2. 2016-01-01 08:00:00 846.0413 Ajmer
3. 2016-01-01 16:00:00 3412.345 Kotada
4. 2016-01-01 17:00:00 3307.476 Kotada
I tried group_by function to form a grouped data frame by Station names and then use the aggregate function to obtain the hourly average. But its not working.
> byStn=df %>% group_by(Station)
> hour_byStn=byStn %>%
+ aggregate(energy,
+ list(hourtime = cut(Datetime, breaks="hour")),
+ mean, na.rm = TRUE)
I obtained the following error : Error in cut(Datetime, breaks = "hour") : object 'Datetime' not found.
Can you please tell me how to do this. This is the first time I am working with time series data and dpylr package as well.
Upvotes: 0
Views: 2070
Reputation: 517
I haven't tested it but you want something along the lines of this...
df %>%
mutate(hourtime = cut(Datetime, breaks='hour')) %>%
group_by(Station, hourtime) %>%
summarise(avg_energy = mean(Energy, na.rm = T))
I would suggest maybe reading up on some basic dplyr
syntax. I referenced this religiously when I first started using it: https://cran.r-project.org/web/packages/dplyr/vignettes/dplyr.html
Upvotes: 2
Reputation: 887971
We can use floor_date
from lubridate
to floor the 'DateTime' by hour
ly interval, use that in group_by
along with 'Station' and get the mean
of 'Energy'
library(lubridate)
library(tidyverse)
df %>%
group_by(Datetime = floor_date(Datetime, "hour"), Station) %>%
summarise(Energy = mean(Energy, na.rm = TRUE))
# A tibble: 4 x 3
# Groups: Datetime [4]
# Datetime Station Energy
# <dttm> <chr> <dbl>
#1 2016-01-01 07:00:00 Ajmer 766.
#2 2016-01-01 08:00:00 Ajmer 846.
#3 2016-01-31 16:00:00 Kotada 3412.
#4 2016-01-31 17:00:00 Kotada 3307.
df <- structure(list(Datetime = structure(c(1451650740, 1451650800,
1451650860, 1451654400, 1451654460, 1454277480, 1454277540, 1454277600,
1454277660), class = c("POSIXct", "POSIXt"), tzone = ""), Energy = c(743.0253,
765.7225, 788.1493, 834.7815, 857.3012, 3427.098, 3397.591, 3344.149,
3270.803), Station = c("Ajmer", "Ajmer", "Ajmer", "Ajmer", "Ajmer",
"Kotada", "Kotada", "Kotada", "Kotada")), row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9"), class = "data.frame")
Upvotes: 3