For loop works perfectly fine, but once I make a function out of it, it suddenly doesn't give the right results in R
问题 I have the following for-loop which does exactly what I want: for (t in 3:20){ XX <- c(rep(0,22)) for (k in (1:(t-2))){ XX[k] <- (theta^(k-1) * (P[t-k] - P[t-k-1])) } X[t] = (1-theta) * sum(XX) + theta^(t-1) P[t] <- D[t] + (0.7/0.3) * X[t] - 0.1*3^2*1*(20-t-1 + (1/0.3)) } However, once I make a function out of and use the function the results are suddenly wrong: BGJS <- function(theta){ for (t in 3:20){ XX <- c(rep(0,22)) for (k in (1:(t-2))){ XX[k] <- (theta^(k-1) * (P[t-k] - P[t-k-1])) } X