wapply | R Documentation |
Iteratively applies function FUN
to subsets of the data defined by a
sliding window centered on each index in turn.
wapply(x, wsize, FUN)
x |
Data; vector, matrix, or data frame. |
wsize |
Window size, in number of indices. |
FUN |
Function to apply to each window of data. If applying to a vector |
For each index, the indices current_index - floor(wsize/2)
to
current_index - floor(wsize/2)
are taken and the function FUN
is applied to that subset of data. At the edges, where floor(wsize/2)
would extend beyond the data, the out-of-range indices are ignored. This means
that at the edges of the data the window size is effectively around half of
the full window size.
The values returned from the function are simplified into a vector if possible, otherwise to a matrix, and as a last resort as a list.
As this method iterates over each index (in a matrix or data frame, each row),
it is of the utmost importance that the data is sorted appropriately (which is
equally applicable for similar functions such as runmed()
).
d <- rnorm(10)
window_median_runmed <- runmed(d,3) # from `stats` package
window_median_wapply <- wapply(d, 3, median) # identical except at edges
d <- data.frame(x = rnorm(400))
d$y <- d$x + rnorm(400)*(sin(seq(0,12,length = 400)+1))
window_correl <- wapply(d, 40, function(x){cor(x[,'x'],x[,'y'])})
plot(window_correl)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.