简体   繁体   English

如何对范围求和并计算R中的序列?

[英]How to sum over range and calculate a series in R?

Here is the formula which I am trying to calculate in R. 这是我尝试在R中计算的公式。

在此处输入图片说明

So far, this is my approach using a simplified example 到目前为止,这是我使用简化示例的方法

t  <- seq(1, 2, 0.1)
expk <- function(k){exp(-2*pi*1i*t*k)}

set.seed(123)
dat <- ts(rnorm(100), start = c(1994,3), frequency = 12)
arfit <- ar(dat, order = 4, aic = FALSE)  # represent \phi in the formula

tmp1 <- numeric(4)  

for (i in seq_along(arfit$ar)){
    ek <- expk(i)
    arphi  <- arfit$ar[i]
    tmp1[i] <-  ek * arphi
    }

tmp2 <- sum(tmp1)

denom = abs(1-tmp2)^2
s2 <- t/denom 

Error : Warning message: In tmp1[i] <- ek * arphi : number of items to replace is not a multiple of replacement length 错误:警告消息:在tmp1 [i] <-ek * arphi中:要替换的项目数不是替换长度的倍数

I was trying to avoid using for loop and tried using sapply as in solutions to this question . 我试图避免使用for循环,并尝试使用sapply作为此问题的解决方案。

denom2 <- abs(1- sapply(seq_along(arfit$ar), function(x)sum(arfit$ar[x]*expf(x))))^2 

but doesnt seem to be correct. 但似乎并不正确。 The problem is to do the sum of the series(over index k) when it is taking values from another vector as well, in this case, t which is in the numerator. 问题是当它也从另一个向量中获取值时,对序列的总和(在索引k上)进行计算,在这种情况下,t是分子中的。 Any solutions ? 有什么解决办法吗?

Any suggestion for a test dataset, maybe using 0 and 1 to check if the calculation is done correctly in this loop here ? 关于测试数据集的任何建议,也许使用0和1来检查计算是否在此循环中正确完成了?

Typing up the answer determined in chat. 输入聊天中确定的答案。 Here's a solution involving vapply . 这是一个涉及vapply的解决方案。

First correct expk to: 首先正确的expk

expk <- function(k){sum(exp(-2*pi*1i*t*k))}

Then you can create this function and vapply it: 然后,您可以创建此函数并将其vapply

myFun <- function(i) return(expk(i) * arfit$ar[i])
tmp2 <- sum(vapply(seq_along(arfit$ar), myFun, complex(1)))

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

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