【问题标题】:Why is this r code not creating a vector?为什么这个 r 代码不创建向量?
【发布时间】:2014-05-27 00:38:05
【问题描述】:

我正在尝试创建一个向量,该向量将保存向量 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

【问题讨论】:

  • 您必须退回它才能使用它。你为什么要打印 then concatenate then store as a4?
  • 我也只尝试了 a4
  • 而且我已经运行了,还是没有出现

标签: r for-loop vector definition


【解决方案1】:

它是在函数体的环境中创建向量。那个环境,因此一旦函数返回,向量就会消失。

获取值有两种方式:返回值并捕获,或者直接修改封闭环境。

要返回值,改变函数如下:

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
}

【讨论】:

    猜你喜欢
    • 2016-05-01
    • 2012-01-27
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 2014-09-01
    相关资源
    最近更新 更多