为什么当 n=1 时系列的第一个元素 TTR::SMA returns NA?

Why TTR::SMA returns NA for first element of series when n=1?

这是我正在看的:

library(TTR)
test <- c(1:10)
test <- SMA(test, n=1)
test
 [1] NA  2  3  4  5  6  7  8  9 10

我问的原因实际上是我有一个脚本可以让你定义 n:

library(TTR)
test <- c(1:10)
Index_Transformation <- 1 #1 means no transformation to the series
test <- SMA(test, n = Index_Transformation)
test
 [1] NA  2  3  4  5  6  7  8  9 10

当 "n =1" 而不是 NA 时,有什么方法可以让 SMA 函数 return 成为系列的第一个元素?

非常感谢您的帮助

您可以使用 rollmean 而不是 zoo

library(zoo)
rollmean(test, 1)
#[1]  1  2  3  4  8  6  7  8  9 10

出于好奇,我正在研究 SMA 函数,它在内部调用 runMean 函数。所以如果你这样做

runMean(test, 1)
# [1] NA  2  3  4  5  6  7  8  9 10

它仍然给出相同的输出。

进一步,runMean以这种方式调用runSum

runSum(x, n)/n

所以如果你现在这样做

runSum(test, 1)
#[1] NA  2  3  4  5  6  7  8  9 10

还有NA。现在 runSum 是一个非常大的函数,原始 NA 就是从这里生成的。

所以,如果你仍然必须坚持使用 SMA 功能,你可以添加一个额外的 if 检查说

if (Index_Transformation > 1) # OR (Index_Transformation != 1)
   test <- SMA(test, n = Index_Transformation)

所以 test 仅在 Index_Transformation 大于 1 时才更改,如果为 1 则保持原样。