[R] ewma help

Leeds, Mark (IED) Mark.Leeds at morganstanley.com
Wed Jan 3 20:20:17 CET 2007


I wrote my own ewma function to deal with the somewhat odd way that
filter handles missing values.
The function I wrote works as long as the NA isn't first but when it is
first I still get a zero in the output.
I'm not expert enough to look at filter and undeerstand what it is
doing.

# 1)  THE FIRST CASE DOESN'T WORK
# I WOULD PREFER A 1 IN THE SECOND ELEMENT OF THE OUTPUT
# BECAUSE THAT IS THE INITIAL NON NA VALUE OF THE SERIES
# I DON"T KNOW WHY A ZERO GETS THERE AND THAT
# MAKES THE REST OF THE SERIES WRONG BECAUSE IT'S
#A RECURSIVE RELATIONSHIP. BASICALLY
#I PREFER THE OUTPUT TO BE THE SAME AS THE SECOND SET OF OUTPUT :
# 1 NA
# 2 1.00
# 3 1.50
# 4 2.25
# WITH THE NA JUST IN A DIFFERENT PLACE

x<-zoo(matrix(c(NA,1,2,3),nc=1))
ewma(x,lambda=0.5)

1 NA
2  0   ( 
3  1
4  2

#=======================================================================
==================================

# 2) THIS CASE DOES WORK

x<-zoo(matrix(c(1,NA,2,3),nc=1))
ewma(x,lambda=0.5)

1 1.00
2   NA
3 1.50
4 2.25



ewma<-function(x,lambda = 1, init = x[1]) {
    # work with 'non-zoo' data for speed and then recombine
    .raw <- coredata(x)
    good.ind <- !is.na(.raw)  # determine good values

    .raw[good.ind] <- filter(lambda * .raw[good.ind], filter=(1-lambda),
        method='recursive', init=coredata(init))
    zoo(.raw, index(x)) # create zoo object for return    
}
--------------------------------------------------------

This is not an offer (or solicitation of an offer) to buy/se...{{dropped}}



More information about the R-help mailing list