filter(x, filter, method = c("convolution", "recursive"), sides = 2, circular = FALSE, init = NULL)
x | a univariate or multivariate time series, a vector, or a matrix with each column representing a univariate component of a multivariate series. |
filter |
a vector of filter coefficients. The first element specifies the
last timepoint used. The last element specifies the earliest
timepoint used.
The same filter coefficients are applied to each univariate component of the time series; that is, to each column of x. Missing values (NAs) are not allowed. The length for filter cannot be longer than the length of time series (nrow(x)) for a convolution filter. |
method | either the string "convolution" or "recursive". Only the beginning of the string is necessary. |
sides |
for convolution filters only.
|
circular | a logical value for convolution filters only. If TRUE, wraps the filter around the ends of the series. If FALSE (the default), do not wrap and set any undefined elements of the filtered series to NA. |
init |
for recursive filters only. A matrix of the values of the filtered
series just prior to the beginning of the input time series.
Must have NROW(init)=length(filter)
and NCOL(init) equal to 1 or the number
of univariate time series in x (NCOL(x)).
The first row of init refers to the values
of the series one time step back from the start
of x. The default is NULL.
A typical init might be the mean of each input series
repeated to the length of the filter. For example:
init=matrix(rep(apply(x,2,mean),length(filter)),nrow=length(filter),byrow=TRUE). |
series <- ts(rt(100, 5), start=c(1974,1), frequency=12) filt <- exp(-((-10:10)^2)/5) # gaussian lowpass filter filt <- filt/sum(filt)# f2series[t] = .3*series[t+1] + .6*series[t] + .1*series[t-1] f2series <- filter(series, c(.3, .6, .1)) # f3series[t] = .3*series[t] + .6*series[t-1] + .1*series[t-2] f3series <- filter(series, c(.3, .6, .1), sides=1) # f4series[t] = .3*series[t] + .6*series[t-1] + .1*series[t-2] f4series <- filter(series, c(.3, .6, .1), sides = 1, circular = TRUE)
x <- rnorm(200) filtx <- c(.4, .1) # fx[t] = .4*fx[t-1] + .1*fx[t-2] + x[t]: fx <- filter(x, filtx, "rec")
# A function to do exponential smoothing: exponential.smooth <- function(x, lambda) { if(length(lambda) > 1) stop("lambda must be a single number") if(lambda > 1 || lambda <= 0) stop("lambda must be between zero and one") xlam <- x * lambda xlam[1] <- x[1] filter(xlam, filter = 1 - lambda, method = "rec") } exponential.smooth(Sdatsets::lynx, .47)
# Generate the Fibonacci Sequence # (30 terms after the initial 1, 1): filter(rep(0, 30), c(1, 1), method="rec", init=c(1, 1))
# NAs and/or factor example for time series. x.fac <- factor(c(1:10, NA, 2:5)) filter(x.fac, c(0.4, 0.1))