简体   繁体   English

R 中的循环求和

[英]Sum in Loop in R

I have a vector of squared autocorrelationcoefficients and want to perform the Ljung-Box-Test in R.我有一个平方自相关系数的向量,想在 R 中执行 Ljung-Box-Test。

So far, I've tried different loops, but nothing really worked and my results don't match the ones you get, when you use box.test.. For instance:到目前为止,我已经尝试了不同的循环,但没有任何效果,而且我的结果与您使用 box.test 时得到的结果不匹配。例如:

for(i in 1:20) {

Q<- n*(n+2)*sum((vector_squared [1:i])/(n-i))

}

No loop needed here:这里不需要循环:

Q <- n*(n+2)*sum(cumsum(vector_squared)/(n-(1:20)))

Also, as correctly pointed out in the comments, you run 20 iterations in the loop and everytime you overwrite what you saved in Q in the last iteration.此外,正如评论中正确指出的那样,您在循环中运行了 20 次迭代,并且每次覆盖上次迭代中保存在Q中的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM