You could use filter(..., filter=rep(1,5)) to get running sums of length 5
to get your answer. The following calls filter once to get the sum of
the negative values in each window and once to get the number of negative
values in each window, then divides to get the means.
f <- function(x, n=5) {
sumNeg <- filter(pmin(x, 0), filter=rep(1,n)) # running sums of negative
values
numNeg <- filter( x < 0, filter=rep(1,n)) # running numbers of
negative values
as.vector(sumNeg/numNeg) # running means of negative values
}
E.g.,> s <- c(0, 2, -3, -2, 1, -2)
> cbind(s, meanNeg = f(s, n=5))
s meanNeg
[1,] 0 NA
[2,] 2 NA
[3,] -3 -2.500000
[4,] -2 -2.333333
[5,] 1 NA
[6,] -2 NA
It is quick for long vectors> ss <- floor(sin(1:1e6)*5) # one million numbers
> system.time(f(ss, 5))
user system elapsed
1.036 0.040 1.079
If you want results at the ends, append (n-1)/2 0's to each end of the
series
and remove the NA's that appear at those positions in the output.
The 'as.vector' is there because filter always returns a 'ts' (a
class of time series
objects), even if the input is a simple vector.
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at
r-project.org] On Behalf
> Of Eko andryanto Prakasa
> Sent: Wednesday, September 26, 2012 8:39 AM
> To: r-help at R-project.org
> Subject: [R] averageif and looping
>
> ?haiii
>
> i want to know, is there?any script in R to measure looping averageif (like
in the excel)
> .......
> for example:
> i have a vector
> row????value
> 1????????0
> 2????????2
> 3????????-3
> 4????????-2
> 5????????1
> 6????????-2
>
> i want to measure the average of the vector for negative value with window
estimation 5
> so first mean is (-3+-2)/2
> ???? second mean is (-3+-2+-2)/3
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.