Compute a simple moving average (running mean).

MoveAvg(x, order, align = c("center", "left", "right"), 
        endrule = c("NA", "keep", "constant"))

Arguments

x

univariate time series.

order

order of moving average.

align

specifies whether result should be centered (default), left-aligned or right-aligned.

endrule

character string indicating how the values at the beginning and the end (of the data) should be treated.

"keep"

keeps the first and last \(k_2\) values at both ends, where \(k_2\) is the half-bandwidth k2 = k %/% 2, i.e., y[j] = x[j] for \(j \in \{1,\ldots,k_2; n-k_2+1,\ldots,n\}\);

"constant"

fill the ends with first and last calculated value in output array (out[1:k2] = out[k2+1])

"NA"

the default, leaves the values to NA, as they are returned by filter.

Details

The implementation is using the function filter to calculate the moving average.

Value

Returns a vector of the same size and same class as x.

Author

Andri Signorell <andri@signorell.net>

See also

There's a faster implementation of running mean in the package caTools runmean() and a slower one in forecast ma(). There's similar code in Midx().

Examples

MoveAvg(AirPassengers, order=5)
#>        Jan   Feb   Mar   Apr   May   Jun   Jul   Aug   Sep   Oct   Nov   Dec
#> 1949    NA    NA 122.4 127.0 133.0 136.2 137.6 137.2 131.0 125.0 118.4 116.4
#> 1950 120.8 127.0 128.4 135.2 144.0 149.8 154.4 156.0 149.0 143.0 138.0 136.4
#> 1951 145.4 155.2 161.6 168.2 178.0 182.2 186.4 184.4 178.0 171.4 165.8 165.0
#> 1952 171.2 178.2 181.6 191.0 201.0 210.8 216.4 218.0 208.8 201.6 192.4 189.8
#> 1953 198.8 211.4 218.4 227.8 241.4 248.6 249.0 245.4 232.8 220.2 206.6 196.8
#> 1954 201.6 211.0 217.6 229.6 252.4 264.0 270.4 269.4 257.2 242.6 232.4 227.2
#> 1955 234.8 248.0 256.2 270.8 297.0 313.0 321.6 322.4 306.8 289.6 277.0 270.0
#> 1956 278.6 293.8 301.8 319.8 347.0 364.6 373.0 370.6 350.0 328.6 310.6 299.8
#> 1957 309.8 325.2 335.0 356.4 389.2 411.4 422.6 421.0 397.6 371.8 346.4 329.2
#> 1958 332.2 340.8 346.2 365.2 399.8 428.4 439.6 438.8 413.8 383.0 354.0 341.6
#> 1959 351.0 368.2 384.8 407.2 448.4 479.0 492.4 489.8 467.8 439.2 410.8 396.4
#> 1960 398.8 418.6 432.0 455.6 501.8 539.2 548.6 546.4 517.4 479.4    NA    NA