1

I am minimizing this function below using the optim function, which works really well. My only problem is that I can't save the W matrix, I am computing inside the function when minimizing. Is there a way to save the W matrix somehow?

W<-c()
GMM_1_stage <- function(beta) {for (i in 1:(nrow(gmm_i))){
  gmm_i[i,]=g_beta(i,beta)}
  gmm_N=t(colSums(gmm_i))%*%colSums(gmm_i) 
  W<-solve((1/(nrow(A)/5))*t(gmm_i)%*%gmm_i) 
  return(gmm_N)
}
GMM_1<-optim(beta_MLE,GMM_1_stage)

Best regards

2 Answers 2

2

Here is a safer version of @mrip's answer that uses a temporary environment rather than <<-:

tempenv <- new.env()
tempenv$xx <- c()
fun<-function(x){
  tempenv$xx[ length(tempenv$xx) + 1 ] <-  x
  x^2    
}    
optimize(fun,c(-1,1))
tempenv$xx

By using the temporary environment you don't need to worry about accidentally writing over an object in the global environment or <<- assigning in an unexpected place.

Sign up to request clarification or add additional context in comments.

Comments

0

You can assign to an object in the global environment (or in a the closest ancestor environment where the variable is defined) using <<-. So, for example, if I wanted to keep track of every value of x during a simple optimization I could do this.

xx<-c()
fun<-function(x){
  xx[length(xx)+1]<<-x
  x^2    
}    
optimize(fun,c(-1,1))
xx
## [1] -2.360680e-01  2.360680e-01  5.278640e-01 -2.775558e-17  4.069010e-05
## [6] -4.069010e-05 -2.775558e-17

In your case, if you only want the last value of W you can replace that line in your code with:

W<<-solve((1/(nrow(A)/5))*t(gmm_i)%*%gmm_i) 

If you want them all, then first set Wlist<-list(), and then in your function set

Wlist[[length(Wlist)+1]]<<-solve((1/(nrow(A)/5))*t(gmm_i)%*%gmm_i)

2 Comments

@GregSnow What's that?
@mrip, the fortunes package contains many quotes representing the wit and wisdom collected from various R related sources over the years, reading random fortunes can be enlightening and/or entertaining. If you install the fortunes package, load it, then run fortune(174) it will give a specific fortune (if the parens are empty then it will give a random fortune).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.