Reputation: 14309
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
}
Upvotes: 0
Views: 291
Reputation: 176648
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)
Upvotes: 1