0

I need to convert a mathemtical equation with summation over an index to code. The sum that needs to be converted to code:

enter image description here

The following is wrong, but its how I've tried to think about it so far.

for (t in 2:T) {
  for (h in 0:M) {
    sum_xp[t] = sum_xp[t] + x[h] * p[t-h]  
    y[t] = b[t] + sum_xp[t] 
  }
}
jrcalabrese
  • 2,184
  • 3
  • 10
  • 30
raykenz
  • 1
  • 1
  • Is `h` in `xh` in your linked formula an index or is it to the power of `h`? – starja Dec 19 '22 at 19:29
  • Please don't post images for code or data. Read these guidelines and edit your question accordingly. https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – John Polo Dec 20 '22 at 02:26

1 Answers1

0

So, my guess is that you want something like this:

for (t in 2:T) {
  sum_xp <- 0
  for (h in 0:(M-1)) {sum_x_p <- sum_xp + x**h * p[t-h]}
  y[t] <- b[t] + sum_xp
}

note that the assignment of y[t] is outside of the for-loop.

Also, it would help to understand what the variables x,y,p etc. look like, but I assume I guessed correctly.

One more thing about Speed:

The funny thing in R is that if you want fast code, you want to avoid big for-loops and instead vectorize your code.

There is all kinds of "apply"-shenanegans in R which can make vectorization easier, but it needs some abstract thinking to implement. As a reference for all kinds of apply-magic I recommend the Advanced R Handbook.

If speed is not so much of an issue, go ahead with the traditional for-loops ;-)