这是一个包含每小时智能电表数据和freq = 24的时间序列.它是在三天内测量的,所以first day[1:24], second[25:48], third[49:72].
我希望在三天内每小时都能得到平均值.例如:
(t[1]+t[25]+t[49])/3
Run Code Online (Sandbox Code Playgroud)
所以我可以在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)
Run Code Online (Sandbox Code Playgroud)
Pau*_*tra 10
因为您没有发布一组易于使用的示例数据,所以我们先生成一些:
time_series = runif(72)
Run Code Online (Sandbox Code Playgroud)
下一步是将数据集的结构从1d向量更改为2d矩阵,这样可以节省大量必须处理索引等等:
time_matrix = matrix(time_series, 24, 3)
Run Code Online (Sandbox Code Playgroud)
并用于apply计算每小时的平均值(如果您愿意apply,请查看plyr包以获得更好的功能,请参阅此链接以获取更多详细信息):
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
Run Code Online (Sandbox Code Playgroud)
但是,如果您使用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()
Run Code Online (Sandbox Code Playgroud)
产量,我认为,你在哪里之后:

在x轴上,一天的小时数,在y轴上的值.
注意:您拥有的数据是时间序列.R具有处理时间序列的特定方式,例如ts函数.我通常使用普通的R数据对象(数组,矩阵),但您可以查看TimeSeries CRAN任务视图,以了解R可以对时间序列执行的操作.
计算每小时意味着使用一个ts对象(受此SO帖子的启发):
# 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
....
Run Code Online (Sandbox Code Playgroud)