时间序列中的每小时平均值

时间:2012-08-22 10:11:14

标签: r time-series

这是一个包含每小时智能电表数据和freq = 24的时间序列。它是在三天内测量的,因此first day[1:24], second[25:48], third[49:72].

我希望在三天内每小时都能得到平均值。例如:

(t[1]+t[25]+t[49])/3

所以我可以在3天内制作24小时的箱形图。

x <- c(0.253, 0.132, 0.144, 0.272, 0.192, 0.132, 0.209, 0.255, 0.131, 
  0.136, 0.267, 0.166, 0.139, 0.238, 0.236, 1.75, 0.32, 0.687, 
  0.528, 1.198, 1.961, 1.171, 0.498, 1.28, 2.267, 2.605, 2.776, 
  4.359, 3.062, 2.264, 1.212, 1.809, 2.536, 2.48, 0.531, 0.515, 
  0.61, 0.867, 0.804, 2.282, 3.016, 0.998, 2.332, 0.612, 0.785, 
  1.292, 2.057, 0.396, 0.455, 0.283, 0.131, 0.147, 0.272, 0.198, 
  0.13, 0.19, 0.257, 0.149, 0.134, 0.251, 0.215, 0.133, 1.755, 
  1.855, 1.938, 1.471, 0.528, 0.842, 0.223, 0.256, 0.239, 0.113)

2 个答案:

答案 0 :(得分:10)

因为您没有发布一组易于使用的示例数据,所以我们先生成一些:

time_series = runif(72)

下一步是将数据集的结构从1d向量更改为2d矩阵,这样可以节省大量必须处理索引等等:

time_matrix = matrix(time_series, 24, 3)

并使用apply计算小时工资(如果您喜欢apply,请查看plyr包以获得更多优秀功能,有关更多详细信息,请参阅this link ):

hourly_means = apply(time_matrix, 1, mean)
> hourly_means
 [1] 0.2954238 0.6791355 0.6113670 0.5775792 0.3614329 0.4414882 0.6206761
 [8] 0.2079882 0.6238492 0.4069143 0.6333607 0.5254185 0.6685191 0.3629751
[15] 0.3715500 0.2637383 0.2730713 0.3170541 0.6053016 0.6550780 0.4031117
[22] 0.6857810 0.4492246 0.4795785

但是,如果您使用ggplot2,则无需预先计算箱图,ggplot2会为您执行此操作:

require(ggplot2)
require(reshape2)
# Notice the use of melt to reshape the dataset a bit
# Also notice the factor to transform Var1 to a categorical dataset
ggplot(aes(x = factor(Var1), y = value), 
       data = melt(time_matrix)) + 
       geom_boxplot()

产量,我认为,你在哪里:

enter image description here

在x轴上,一天的小时数,在y轴上的值。


注意:您拥有的数据是时间序列。 R具有处理时间序列的特定方式,例如ts函数。我通常使用普通的R数据对象(数组,矩阵),但您可以查看TimeSeries CRAN taskview以了解R可以对时间序列做什么。

使用ts对象计算小时数意味着(受此SO post启发):

# Create a ts object
time_ts = ts(time_series, frequency = 24)
# Calculate the mean
> tapply(time_ts, cycle(time_ts), mean)
        1         2         3         4         5         6         7         8 
0.2954238 0.6791355 0.6113670 0.5775792 0.3614329 0.4414882 0.6206761 0.2079882 
        9        10        11        12        13        14        15        16 
0.6238492 0.4069143 0.6333607 0.5254185 0.6685191 0.3629751 0.3715500 0.2637383 
       17        18        19        20        21        22        23        24 
0.2730713 0.3170541 0.6053016 0.6550780 0.4031117 0.6857810 0.4492246 0.4795785 
> aggregate(as.numeric(time_ts), list(hour = cycle(time_ts)), mean)
   hour         x
1     1 0.2954238
2     2 0.6791355
3     3 0.6113670
4     4 0.5775792
....

答案 1 :(得分:3)

您可以使用基本R安装附带的boxplot功能轻松完成此操作。只需使用原始系列创建一个data.frame,并使用索引标识每天的小时数。

Data <- data.frame(series=x, time=rep(1:24,3))
boxplot(series ~ time, data=Data)

boxplot output

相关问题