0

I am writing a program that optimizes a function, and I need to assign a variable such that it can be used for the next iteration inside the function. This example is not reproducible, but it should show the general point:

gmmobjnoinst=function(theta2){

    deltanew <- innerloop(theta2,delta0)  #the thing using the input (delta0)
    delta0 <- deltanew                    #the thing I want to be saved for next iteration

    theta1hat <- solve(t(x1)%*%x1)%*%t(X)%*%deltanew
    w <- deltanew-x1%*%theta1hat


    gmmobj <- t(w)%*%w

    return(gmmobj)

}

Will the next iteration in the optimization:

optmodel3nevo=optim(approxstartingnevo,gmmobjnoinst,
    method="L-BFGS-B", hessian=TRUE,lower=c(0,0,0,0,-Inf,-Inf,-Inf,-Inf,-Inf,-Inf,-Inf,
        -Inf,-Inf),upper=rep(Inf,13),
    control=list(maxit=20000, fnscale=1))

be using delta0 into the formula for deltanew ? What if I used <<- instead of <-? That seems like it MAY do what I want, but I am having a hard time checking..

wolfsatthedoor
  • 7,163
  • 18
  • 46
  • 90

1 Answers1

1

You can do it this way:

gmmobjnoinst.make <- function(delta.ini){
   delta0 <- delta.ini

   gmmobjnoints <- function(theta2){

     deltanew <- innerloop(theta2,delta0)  #the thing using the input (delta0)
     delta0 <<- deltanew                    #the thing I want to be saved for next iteration

     theta1hat <- solve(t(x1)%*%x1)%*%t(X)%*%deltanew
     w <- deltanew-x1%*%theta1hat

     gmmobj <- t(w)%*%w

     return(gmmobj)
   }

   return(gmmobjnoints)
}

gmmobjnoinst <- mgmmobjnoinst.make(0)

This way delta0 becames an static variable.

Alnair
  • 938
  • 8
  • 10
  • But then which function do I optimize? Are you sure this does the right thing? – wolfsatthedoor Apr 02 '14 at 18:48
  • I already used this trick and it works. I found a link I found this answer for first time. May be that example is more clear: [link](http://stackoverflow.com/questions/1088639/static-variables-in-r) – Alnair Apr 02 '14 at 18:52
  • You must optimize `gmmobjnoinst`. Maybe is a bit confusing because this name is used inside the `.make` function and outside, but at the end the 'variable' `gmmobjnoints` contains the function with the same name defined inside the `.make` and this function has `delta0` in his enviroment. – Alnair Apr 02 '14 at 18:56
  • In your example, do I need delta0 <<- deltanew ? The link seems to suggest that no? – wolfsatthedoor Apr 02 '14 at 19:23
  • 1
    Yes, you are right. It was a mistake. I corrected it. – Alnair Apr 02 '14 at 20:16