簡體   English   中英

雙邊移動平均線?

[英]two-sided moving average?

如何獲得雙向“移動平均線”,這是一個從矢量的左右平均n個數字的函數,並根據它們與中心值的距離給出它們的權重?

我嘗試使用TTR,但其移動平均線僅從左到右工作,並將最左邊的值設置為NA。 所以我不能使用平滑的矢量作為smooth.spline的輸入

在動物園包中, 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 =“partial”或rule = 3 問題在於,隨着新的結束規則被添加到開發版本(現在有3個和第4個將在其發布之前添加),每個規則都有一個單獨的參數,使用戶界面變得混亂。 rule是與更一致的approx在R的核心事實上, rule=1rule=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")

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

你可以和kernapply一起嘗試kernel (在第一頁的末尾有一些例子)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM