Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting more details from optim function from R

I'm not very familiar with the optim function, and I wanted to get these informations from its results: a) how many iterations were needed for achieving the result? and b) to plot the sequence of partial solutions, that is, the solution obtained in the end of each iteration.

My code until now looks like this:

  f1 <- function(x) {
  x1 <- x[1]
  x2 <- x[2]
  x1^2 + 3*x2^2
}

res <- optim(c(1,1), f1, method="CG")

How can I improve it to get further information?

Thanks in advance

like image 481
gcolucci Avatar asked Dec 07 '22 01:12

gcolucci


1 Answers

You could modify your function to store the values that are passed into it into a global list.

i <- 0  
vals <- list()
f1 <- function(x) {
  i <<- i+1
  vals[[i]] <<- x

  x1 <- x[1]
  x2 <- x[2]
  x1^2 + 3*x2^2  
}

res <- optim(c(1,1), f1, method="CG")

Now if you examine i and vals after you run the function you can see what happened. If you want to see the values while optim is running throw a print statement into the function as well.

like image 157
Dason Avatar answered Dec 29 '22 05:12

Dason