Bilateral Moving Average?

how to get a two-way "moving average", which is a function that averages n numbers to the right and left of the vector and gives their weights in accordance with their distance from the center value?

I tried to use TTR, but its moving averages only work from left to right and set the leftmost values ​​as NA. Therefore, I cannot use this smoothed vector as a contribution to smooth.spline

+5
source share
3 answers

The zoo package rollmeanand rollapplythere are arguments that allow multiple options.

library(zoo)
x <- seq(10)^2

# no NAs at end
rollmean(x, 3)

# NAs at ends
rollmean(x, 3, na.pad = TRUE)

# weighted mean
rollapply(zoo(x), 3, function(x) c(1, 2, 1) %*% x / 4) 

# at ends take means of less than 3 points - needs devel version
# partial= is in development and at this point must use na.rm = TRUE to use partial
source("http://r-forge.r-project.org/scm/viewvc.php/*checkout*/pkg/zoo/R/rollapply.R?revision=802&root=zoo")
rollapply(zoo(x), 3, mean, partial = TRUE, na.rm = TRUE)

EDIT:

, , , partial = TRUE = "partial" rule = 3. , ( 3, 4), , . , rule approx R. rule=1 rule=2 rollapply approx ( R) . mean , rollmean, rule="partial" , , .

source("http://r-forge.r-project.org/scm/viewvc.php/*checkout*/pkg/zoo/R/rollapply.R?revision=815&root=zoo")
rollapply(zoo(x), 3, (mean), rule = "partial")
+9

filter() sides:

filter                  package:stats             R Documentation

Linear Filtering on a Time Series

Description:

     Applies linear filtering to a univariate time series or to each
     series separately of a multivariate time series.

Usage:

     filter(x, filter, method = c("convolution", "recursive"),
            sides = 2, circular = FALSE, init)

Arguments:
[...] 
   sides: for convolution filters only. If ‘sides=1’ the filter
          coefficients are for past values only; if ‘sides=2’ they are
          centred around lag 0. In this case the length of the filter
          should be odd, but if it is even, more of the filter is
          forward in time than backward.
+5

You can try kernelalong with kernapply(there are some examples at the end of the first page).

+2
source

All Articles