Sometimes we need to extract and analyse parts of a dataset (e.g. a vector, or the columns or rows of a data frame) along a moving (aka sliding, rolling, running) window. The jumping.window function, included in the newly released DeadCanMove package (Barbosa et al. 2014), extracts a moving window with (currently) no overlap between windows, and with the possibility of a gap (whose size is defined by the user) between windows:
jumping.window <- function(x, window.size, gap.size) { window.indices <- integer(0) for (i in 1 : window.size) { window.indices <- c(window.indices, seq(from = i, to = length(x), by = window.size + gap.size)) } window.indices <- sort(window.indices) sampl.windows <- vector[window.indices] return(sampl.windows) } # end jumping.window function
Usage examples:
Paste the whole text of the function above in R, press enter, and then paste the following commands to check out how the function works:
jumping.window(x = 1:20, window.size = 1, gap.size = 0) jumping.window(x = 1:20, window.size = 1, gap.size = 1) jumping.window(x = 6:52, window.size = 5, gap.size = 10) jumping.window(x = c(1, 3, 4, 6, 9, 10, 11), window.size = 3, gap.size = 2) jumping.window(x = c("air", "bird", "cloud", "deep", "elephant", "goat"), window.size = 2, gap.size = 2) # to extract jumping-window columns from a table: head(CO2) CO2jump <- CO2[ , jumping.window(x = 1:ncol(CO2), window.size = 2, gap.size = 1)] head(CO2jump)
References:
Barbosa A.M., Marques J.T., Santos S.M., Lourenço A., Medinas D., Beja P. & Mira A. (2014) DeadCanMove: Assess how spatial roadkill patterns change with temporal sampling scheme. R package version 0.1 (available at http://deadcanmove.r-forge.r-project.org)