roll_median: Rolling Median

View source: R/roll_median.R

roll_medianR Documentation

Rolling Median

Description

Fast, center-aligned rolling medians using C++/Rcpp. Additional performance gains can be achieved by skipping increment values between calculations.

The roll_median function can be used to replace outliers detected by the roll_hampel function. See example below.

Usage

roll_median(x, n = 7, increment = 1)

Arguments

x

an R numeric vector

n

integer window size

increment

integer shift to use when sliding the window to the next location

Details

The window size n is interpreted as the full window length. Values within n/2 of the beginning or end of x are set to NA.

Setting increment to a value greater than one will result in NAs for all skipped-over indices.

Value

A vector of rolling median values of the same length as x.

See Also

roll_hampel

Examples

a <- jitter(sin(0.1*seq(1e4)),amount=0.2)
indices <- sample(seq(1e4),20)
a[indices] <- a[indices]*10

# Outlier detection
b <- roll_hampel(a,10)
threshold <- 6
outliers <- which(b > threshold)

# Outlier replacement with median values
a_fixed <- a
a_fixed[outliers] <- roll_median(a,10)[outliers]

# Set up two plots
layout(matrix(seq(2)))
plot(a,type='l', col='gray60', main="Outliers detected")
points(outliers,a[outliers], col='red', lwd=2)

plot(a_fixed,type='l', col='gray60',
     main="Outliers replaced with rolling median")
points(outliers,a_fixed[outliers], col='red', lwd=2)

seismicRoll documentation built on Aug. 22, 2023, 9:13 a.m.