有什么方法可以强制Zoo :: RollMean函数返回与输入相同长度的向量? (还是使用其他功能?)

StackOverflow https://stackoverflow.com/questions/4422363

  •  09-10-2019
  •  | 
  •  

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)

输出:

      [,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

但是,当我尝试将其转换为:

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

我想使用一个足够聪明的函数,如果它在向量的两端没有数据并计算输出的数据,则只会根据其拥有的数据来计算输出。因此,例如在输入[1]中,它将仅计算出均值

有帮助吗?

解决方案

看着那(这 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

除非您需要这些东西作为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

由于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)

您将很难判断这两者之间的区别Comparison of direct smooth and smooth of MA

曲线在开始时偏离MA的估计。

其他提示

尽管这是一个古老的问题,但对于任何阅读本文的人来说,希望它会有所帮助。

使用rollapply与函数均值,partial = true将保持无法计算函数的初始值。

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

??rollapply 
??rollapplyr # for right aligned moving average

阅读文档会真正受益。看 ?rollmean, ,特别是 na.padalign 参数。

到目前为止,这个问题被三个体验R编码器视为模棱两可,但似乎您确实需要某种丢失手段的推断价值。您是要在开始时还是要估算的值,还是终点不清楚。该代码将返回一个右对方的向量,并用第一个NOT-NA值替换开头NA。如果您想与左对齐的Rollmeans一起工作,也将在动物园中具有Na.locf功能。

long.roll <- function(input, k) { rtroll <-  
                           rollmean(input, k, align="right", na.pad=TRUE)
                return(c(rep(rtroll[k], k-1), rtroll[-(1:(k-1))]) ) }
long.roll(input,4)
#  [1] 4.50 4.50 4.50 4.50 4.25 4.75 4.25 4.00 5.00 3.75 5.25 5.00 5.25
# [14] 5.25
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top