2014-08-28 59 views
0

我想每五分鐘計算一次能見度。我嘗試使用循環,但它不成功。有人可以幫助解決它嗎? 數據連接如何使用R計算循環中每五分鐘的平均值?

 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]) 
} 
+0

請使用'dput()'提供您的數據。 – 2014-08-28 17:36:00

回答

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 
0

您可以從動物園包

示例代碼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