问题
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[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))
}
}
Can someone find the mistake?
回答1:
Change <-
and =
to <<-
as your scope is different in functions.
?"<<-"
The operators <-
and =
assign into the environment in which they are evaluated. ...
The operators <<-
and ->>
are normally only used in functions, and cause a search to be made through parent environments for an existing definition of the variable being assigned. ...
来源:https://stackoverflow.com/questions/56634717/for-loop-works-perfectly-fine-but-once-i-make-a-function-out-of-it-it-suddenly