0

I would like to implement the following rollscale function that scales (centers and normalizes i.e. subtract mu and divide by sigma) the dataset x but instead of doing it using a global mu and sigma they are computed within a rolling window on the seen data. I came out with the following but don't know how to define the function parameter on the third rollapplyr i.e. how do I know what the current position is?

library(zoo)
rollscale <- function(x, k) {
    mu <- rollapplyr(x, k, mean)
    sigma <- rollapplyr(x, k, sd)
    x <- rollapplyr(x, k, function(x) ???)              
}

The simple scale function would be:

scale <- function(x) {
    mu <- mean(x)
    sigma <- sd(x)
    x <- (x - mu)/sigma         
}
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
SkyWalker
  • 13,729
  • 18
  • 91
  • 187
  • 2
    Why not just use `rollapplyr(x, k, scale)`? – Joshua Ulrich Aug 27 '13 at 13:00
  • pretty darn good idea! :D didn't think there is scale, how about if I just want to have say normalize by two times sigma? :) ok ok you gave me the answer. Please answer and I will accept. – SkyWalker Aug 27 '13 at 13:09

1 Answers1

1

You're making this more complicated than it is. You have a scale function, and you want to apply it on a rolling basis. This is exactly what rollapply does!

scale <- function(x) {
    mu <- mean(x)
    sigma <- sd(x)
    x <- (x - mu)/sigma         
}
scaled.data <- rollapplyr(Data, 5, scale)
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418