简体   繁体   中英

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

Here is the formula which I am trying to calculate in 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

I was trying to avoid using for loop and tried using sapply as in solutions to this question .

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. 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 ?

Typing up the answer determined in chat. Here's a solution involving vapply .

First correct expk to:

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

Then you can create this function and vapply it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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