For loop works perfectly fine, but once I make a function out of it, it suddenly doesn't give the right results in R

爷,独闯天下 提交于 2021-01-29 17:37:52

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!