[R] Moving standard deviation?
Martin Maechler
maechler at stat.math.ethz.ch
Tue Dec 14 11:46:47 CET 2004
>>>>> "bogdan" == bogdan romocea <br44114 at yahoo.com>
>>>>> on Mon, 13 Dec 2004 12:26:46 -0800 (PST) writes:
bogdan> A simple for loop does the job. Why not write your own function?
movsd <- function(series,lag)
{
movingsd <- vector(mode="numeric")
for (i in lag:length(series))
{
movingsd[i] <- sd(series[(i-lag+1):i])
}
assign("movingsd",movingsd,.GlobalEnv)
}
bogdan> This is very efficient: it takes (much) less time to write from
bogdan> scratch than to look for an existing function.
yes, it's fine, but the assign() line is really something so
much not-recommendable `` I can't let go through '' :
Your movsd() provides a function with ``side effect'' : it
"suddenly" creates a global variable 'movingsd' {overwriting
another one, if there was one} instead of doing
the most natural thing for an S (or R) function: *return* it's
computation:
So, please, use instead something like
movsd <- function(series,lag)
{
msd <- vector(mode="numeric")
for (i in lag:length(series))
{
msd[i] <- sd(series[(i-lag+1):i])
}
msd
}
and then things like
sy1.3 <- movsd(y1, 3)
sy1.5 <- movsd(y1, 5)
sy2.5 <- movsd(y2, 5)
etc.
More information about the R-help
mailing list