for循环工作得很好,但是一旦我用它做一个函数,它突然就不会在R中给出正确的结果 [英] For loop works perfectly fine, but once I make a function out of it, it suddenly doesn't give the right results in R
本文介绍了for循环工作得很好,但是一旦我用它做一个函数,它突然就不会在R中给出正确的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有下面的for循环,正是我想要的:
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))
}
}
有人可以找到错误吗?
推荐答案
将<-
和 =
更改为<<-
因为您的范围在功能上有所不同.
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. ...
这篇关于for循环工作得很好,但是一旦我用它做一个函数,它突然就不会在R中给出正确的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文