2010-12-11 130 views
5

如何獲得雙側「移動平均數」,即從矢量的右側和左側平均n個數字並根據它們與中心值的距離給出權重的函數?雙面移動平均?

我試着使用TTR,但它的移動平均線只能從左到右工作,並將最左側的值設置爲NA。所以我不能使用那個平滑的矢量作爲smooth.spline的輸入。

回答

8

在動物園包rollmeanrollapply有參數,允許的許多變化。

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) 

編輯:

注意,因爲這被寫動物園的開發版本已更改,這樣,而不是寫partial = TRUE一個寫入規則=「部分」或rule = 3的。問題在於,隨着開發版本中添加新的結束規則(現在有3個,在發佈之前會添加4個),爲每個開發版本分別提供一個參數,使用戶界面變得混亂。另外rule與R的核心中的approx更一致。事實上,rule=1rule=2rollapplyapprox(來自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") 
+0

但爲什麼rollmean的輸出總是比輸入短一個元素? – rsk82 2010-12-12 14:51:07

5

看那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.