how to calculate mean for every five minutes in a loop by using R?

与世无争的帅哥 提交于 2019-12-25 07:04:18

问题


I would like to calculate visibility mean every five minutes. I try to use for loop, but it is not successful. Can someone help to fix it? The data is attached

        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

Here is the code

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

回答1:


This will work for your sample data

#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



回答2:


You can use rollapply from zoo package

Sample code

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


来源:https://stackoverflow.com/questions/25554565/how-to-calculate-mean-for-every-five-minutes-in-a-loop-by-using-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!