Skip to contents

Apply a Butterworth digital filter to vector data with signal::butter() and signal::filtfilt() which handles 'edges' better at the start and end of the data.

Usage

filtfilt_edges(
  x,
  n = 1,
  W,
  type = c("low", "high", "stop", "pass"),
  edges = c("rev", "rep1", "none")
)

Arguments

x

A numeric vector.

n

An integer scalar defining the filter order number.

W

A numeric scalar or two-element vector defining the fractional critical frequency of the filter (see Details).

type

Digital filter type (see Details).

"low"

For a low-pass filter (default).

"high"

For a high-pass filter.

"stop"

For a stop-band (band-reject) filter.

"pass"

For a pass-band filter.

edges

Indicates how to pad x.

"rev"

Will pad x with the preceding 10% data in reverse sequence (default).

"rep1"

Will pad x with the last preceding value.

"none"

Will return the default signal::filtfilt() output.

Value

A numeric vector of the same length as x.

Details

Applies a centred (two-pass symmetrical) Butterworth digital filter from signal::butter() and signal::filtfilt().

The filter order is defined by n, an integer scalar typically in the range n = [1, 10].

The critical (cutoff) frequency is defined by W, a numeric scalar for low-pass and high-pass filters, or a two-element vector c(low, high) defining the lower and upper bands for stop-band and pass-band filters.

Low-pass and high-pass filters allow only frequencies lower or higher than the critical frequency W to be passed through as the output signal, respectively. Stop-band defines a critical range of frequencies which are rejected from the output signal. Pass-band defines a critical range of frequencies which are passed through as the output signal.

Examples

set.seed(13)
sin <- sin(2 * pi * 1:150 / 50) * 20 + 40
noise <- rnorm(150, mean = 0, sd = 6)
noisy_sin <- sin + noise
filt_without_edge <- filtfilt_edges(x = noisy_sin, n = 2, W = 0.1, edges = "none")
filt_with_edge <- filtfilt_edges(x = noisy_sin, n = 2, W = 0.1, edges = "rep1")

if (FALSE) { # \dontrun{
plot(noisy_sin, type = "l")
lines(filt_without_edge, col = "red", lwd = 4)
lines(filt_with_edge, col = "blue", lwd = 4)
} # }