如何使用R?

时间:2016-01-02 13:17:43

标签: r

我正在尝试使用此代码计算8天的累积降雨量,但似乎效果不佳。

chuva $ Precipitacao它是我每日降雨量的矢量,长度为5601。

 rain<-chuva$Precipitacao 
j=1
rain8<-vector()
for (i in 1:800){
   rain8<-rbind(rain8, (rain[j]+rain[j+1]+rain[j+2]+rain[j+3]+
                     rain[j+4]+rain[j+5]+rain[j+6]+rain[j+7]));
  j=i+7
}

2 个答案:

答案 0 :(得分:3)

您可以尝试动物园包中的以下一个衬垫rollapply功能。

rain8<-rollapply(rain, 'your main vector
                 8,    'The number of consecutive data points
                 sum)  'The function you want to apply

答案 1 :(得分:2)

你可以这样做:

## if you want to calculate moving sum of 8 days
rain <- chuva$Precipitacao
rain8 <- vector()
for (i in rain[1:5594]){
    rain8 <- c(rain8, sum(rain[i:i + 7]))
}

## if you want to calculate sum for each separate period of 8 days
rain <- chuva$Precipitacao
rain8 <- vector()
for (i in seq(1, length(rain), 7)){
    rain8 <- c(rain8, sum(rain[i:i + 7]))
}