roll_median | R Documentation |
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.
roll_median(x, n = 7, increment = 1)
x |
an R numeric vector |
n |
integer window size |
increment |
integer shift to use when sliding the window to the next location |
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 NA
s for all skipped-over indices.
A vector of rolling median values of the same length as x
.
roll_hampel
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)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.