Cyrillm_44
Cyrillm_44

Reputation: 711

Storing information during optim()

I have a general function I have provided an example below if simple linear regression:

x = 1:30
y = 0.7 * x + 32
Data = rnorm(30, mean = y, sd = 2.5);

lin = function(pars = c(grad,cons)) {
  expec = pars[1] * x + pars[2];
  SSE = sum((Data - expec)^2)
  return(SSE)
}

start_vals = c(0.2,10)
lin(start_vals)
estimates = optim(par = start_vals, fn = lin);

## plot the data
Fit = estimates$par[1] * x + estimates$par[2]
plot(x,Data)
lines(x, Fit, col = "red")

So that's straight forward. What I want is to store the expectation for the last set of parameters, so that once I have finished optimizing I can view them. I have tried using a global container and trying to populating it if the function is executed but it doesn't work, e.g

Expectation = c();
lin = function(pars = c(grad,cons)) {
  expec = pars[1] * x + pars[2];
  Expectation = expec;
  SSE = sum((Data - expec)^2)
  return(SSE)
}

start_vals = c(0.2,10)
estimates = optim(par = start_vals, fn = lin);
Expectation ## print the expectation that would relate to estimates$par

I know that this is trivial to do outside of the function, but my actual problem (which is analogous to this) is much more complex. Basically I need to return internal information that can't be retrospectively calculated. Any help is much appreciated.

Upvotes: 1

Views: 38

Answers (1)

myincas
myincas

Reputation: 1530

you should use <<- instead of = in your lin function, Expectation <<- expec,The operators <<- and ->> are normally only used in functions, and cause a search to be made through parent environments for an existing definition of the variable being assigned.

Upvotes: 1

Related Questions