有没有办法强制zoo :: rollmean函数返回一个与它的输入长度相同的向量?(或者可能使用其他功能?)

rsk*_*k82 4 r zoo

input = cbind(c(3,7,3,5,2,9,1,4,6,4,7,3,7,4))
library(zoo)
output = cbind(rollmean(input,4))
print(input)
print(output)
Run Code Online (Sandbox Code Playgroud)

输出:

      [,1]
 [1,]    3
 [2,]    7
 [3,]    3
 [4,]    5
 [5,]    2
 [6,]    9
 [7,]    1
 [8,]    4
 [9,]    6
[10,]    4
[11,]    7
[12,]    3
[13,]    7
[14,]    4
      [,1]
 [1,] 4.50
 [2,] 4.25
 [3,] 4.75
 [4,] 4.25
 [5,] 4.00
 [6,] 5.00
 [7,] 3.75
 [8,] 5.25
 [9,] 5.00
[10,] 5.25
[11,] 5.25
Run Code Online (Sandbox Code Playgroud)

但是当我试图解决它时:

Error in cbind(input, output) :
  number of rows of matrices must match (see arg 2)
Calls: print -> cbind
Execution halted
Run Code Online (Sandbox Code Playgroud)

我想使用一个足够智能的函数,如果它不能在向量的两端获取数据并且仅根据它所拥有的数据计算输出,则不要放弃.例如,在输入[1]中,它将仅计算右边的平均值

Rei*_*son 12

查看na.pad参数rollmean(),并将其设置为TRUE.错过了最后一点; 所以你还需要将手段对齐到右边:

> input <- c(3,7,3,5,2,9,1,4,6,4,7,3,7,4)
> rollmean(input, 4, na.pad = TRUE, align = "right")
 [1]   NA   NA   NA 4.50 4.25 4.75 4.25 4.00 5.00 3.75 5.25 5.00 5.25 5.25
Run Code Online (Sandbox Code Playgroud)

除非您需要将这些内容作为1列矩阵,否则请放弃cbind()调用.

好的,从进一步的澄清看来,您似乎想要计算一些与结果向量中的其他方法无法真正比​​较的方法.但如果你必须......

> k <- 4
> c( cumsum(input[1:(k-1)]) / 1:(k-1), rollmean(input, k, align = "right") )
 [1] 3.000000 5.000000 4.333333 4.500000 4.250000 4.750000 4.250000 4.000000
 [9] 5.000000 3.750000 5.250000 5.000000 5.250000 5.250000
Run Code Online (Sandbox Code Playgroud)

由于OP有兴趣估计MA然后拟合样条曲线,因此通过这样做而不是直接从数据估计样条曲线来查看获得的内容可能是有益的.

> ## model observed data
> mod <- smooth.spline(seq_along(input), input, df = 3)
> ## plot data and fitted spline
> plot(seq_along(input), input)
> lines(predict(mod, seq_along(input)), col = "red", lwd = 2)
> ## model the fudged MA
> mod2 <- smooth.spline(seq_along(input),
+                       c( cumsum(input[1:(k-1)]) / 1:(k-1),
+                         rollmean(input, k, align = "right") ), df = 3)
> ## add this estimated spline
> lines(predict(mod2, seq_along(input)), col = "blue", lwd = 2)
Run Code Online (Sandbox Code Playgroud)

你很难说出这两者之间的区别 MA直接光滑平滑的比较

并且曲线在开始强制估计MA时偏离最大.


Anu*_*sha 9

虽然这是一个老问题,但对于读这篇文章的人来说,希望它有所帮助.

使用具有函数mean的rollapply和partial = TRUE将保持无法计算函数的初始值.

x <- rollapply(input, width = 5, FUN = mean, align = "centre", partial = TRUE")

??rollapply 
??rollapplyr # for right aligned moving average
Run Code Online (Sandbox Code Playgroud)