0

I am trying to create a vector that will save the vector vprime for graphing later, but it wont't show up in my local environment (it is not writing the vector). Any ideas??

Thanks!!

###plot all three at once###

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
Jake_Mill22
  • 39
  • 1
  • 7

1 Answers1

3

It is creating the vector in the environment of the function body. That environment, and thus the vector goes away once the function returns.

There are two ways to get the value: Return the value and capture it, or modify the enclosing environment directly.

To return the value, change the function as follows:

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)

Modifying the enclosing environment seems easy, but leads to trouble down the road, so this approach should be avoided. But to do this, change the function as follows:

iterater<-function(space){
   # ....

   # Note <<- instead of <-
   a4<<-vprime3
   plot(space,vprime3, type="p", xlab="State Space", ylab="Value") # and plot this graph
}
Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112