wapply: Apply a function to windows of the data

View source: R/wapply.R

wapplyR Documentation

Apply a function to windows of the data

Description

Iteratively applies function FUN to subsets of the data defined by a sliding window centered on each index in turn.

Usage

wapply(x, wsize, FUN)

Arguments

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 FUN can be a simple function like median (see example); otherwise it should be defined as having one argument, x, indicating data.

Details

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()).

Examples


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)


akcochrane/ACmisc documentation built on Nov. 24, 2024, 11:22 a.m.