我正在尝试创建一个向量来保存向量vprime以便稍后进行绘图,但它不会出现在我的本地环境中(它不会写入向量)。任何想法??
谢谢!
###一下子全部三个###
space<-seq(length=100, from=0, to=7.2) ##Create a sequence of 100 values ending at the point where value goes negative
A<- 4 #take a as given
alpha<-0.3 #take alpha as given
beta<-0.98 #take beta as given
vprime3 <- c(1:100) ##create a vector length 100 to be replaced later
t_vj3 <- c(1:100) ##create a vector length 100 to be replaced later
iterater<-function(space){ ##create a function to perform the iteration
for(i in 1:100){ ##create for loop for one of the state space (varying k+1)
for(j in 1:100){ ##create for loop for another axis of the state spcae (varying k)
if((A*(space[i]^alpha)-space[j])<0){ #plug in the law of motion
t_vj3[j]=-99 #and have a case for negative consumption so it does not take a negative log
}
else {
t_vj3[j+1] <- (log(A*(space[i]^alpha)-space[j])+ beta*t_vj3[j]) #have the law of motion for positive values
}
}
vprime3[i]<-max(t_vj3) #and create a vector of the maximum values, or the value functions
}
a4<-vprime3
plot(space,vprime3, type="p", xlab="State Space", ylab="Value") # and plot this graph
}
iterater(space) #call the function
答案 0 :(得分:3)
它正在函数体的环境中创建向量。该环境,因此一旦函数返回,向量就会消失。
获取值有两种方法:返回值并捕获它,或直接修改封闭环境。
要返回值,请按如下所示更改功能:
iterater<-function(space){
# ....
a4<-vprime3
plot(space,vprime3, type="p", xlab="State Space", ylab="Value") # and plot this graph
# Added line
return(a4)
}
## Call iterater, saving the value:
a4 <- iterater(space)
修改封闭环境似乎很容易,但是会导致麻烦,所以应该避免这种方法。但要执行此操作,请按如下所示更改功能:
iterater<-function(space){
# ....
# Note <<- instead of <-
a4<<-vprime3
plot(space,vprime3, type="p", xlab="State Space", ylab="Value") # and plot this graph
}