如何使用R计算循环中每五分钟的平均值?

时间:2014-08-28 17:22:42

标签: r for-loop increment mean

我想每五分钟计算一次能见度。我尝试使用for循环,但它没有成功。有人可以帮忙修复它吗? 数据已附加

        time    V1  harmonic_ave    visibility
1   00:00   0.17652184  0   5.6650213
2   00:01   0.23150237  0   4.3196102
3   00:02   0.35068959  0   2.8515246
4   00:03   0.48666769  0   2.0547902
5   00:04   0.54693229  0   1.8283799
6   00:05   0.58146776  0   1.7197858
7   00:06   0.69513934  0   1.4385605
8   00:07   0.90809604  0   1.1012051
9   00:08   1.02237511  0   0.9781146
10  00:09   0.94165997  0   1.0619545
11  00:10   0.74532231  0   1.3417014

这是代码

for (i in seq(from=1,to=1440,by=5)) {
  AWIv<-mean(AWI1Hmean_140607$visibility[i:i+5])
}

2 个答案:

答案 0 :(得分:0)

这适用于您的样本数据

#input relevant vector only
a <- c(
5.6650213,
4.3196102,
2.8515246,
2.0547902,
1.8283799,
1.7197858,
1.4385605,
1.1012051,
0.9781146,
1.0619545,
1.3417014)

# create output vector
a2 <- vector(mode= "numeric", length= length(a)/5)

# execute loop
for (i in 1:length(a2)) {
  a2[i] <- mean(a[(5*i-4):(5*i)])
}

# check output
a2
[1] 3.343865 1.259924

答案 1 :(得分:0)

您可以使用zoo package中的rollapply

示例代码

library(zoo)
data1 <- read.table(header=TRUE, text='
id time    V1  harmonic_ave    visibility
1   00:00   0.17652184  0   5.6650213
2   00:01   0.23150237  0   4.3196102
3   00:02   0.35068959  0   2.8515246
4   00:03   0.48666769  0   2.0547902
5   00:04   0.54693229  0   1.8283799
6   00:05   0.58146776  0   1.7197858
7   00:06   0.69513934  0   1.4385605
8   00:07   0.90809604  0   1.1012051
9   00:08   1.02237511  0   0.9781146
10  00:09   0.94165997  0   1.0619545
11  00:10   0.74532231  0   1.3417014
')
# Convert to zoo object
z <- zoo(data1$visibility, order.by=data1$time)
# Calculate mean for nonoverlapping groups of 5
# align="left": timestamp is taken from the leftmost value.
rollapply(z, 5, mean, by=5, align="left") 

   00:00    00:05 
3.343865 1.259924