# 如何获取具有多列的时间序列数据框中的每小时平均值

##### 问题描述投票：0回答：2

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
``````

``````     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
``````

``````> byStn=df %>% group_by(Station)
> hour_byStn=byStn %>%
+            aggregate(energy,
+                       list(hourtime = cut(Datetime, breaks="hour")),
+                       mean, na.rm = TRUE)
``````

r dplyr time-series
##### 2个回答
1

``````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.
``````

### data

``````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",
"2", "3", "4", "5", "6", "7", "8", "9"), class = "data.frame")
``````

1

``````df %>%
mutate(hourtime = cut(Datetime, breaks='hour')) %>%
group_by(Station, hourtime) %>%
summarise(avg_energy = mean(Energy, na.rm = T))
``````