# [R] probl with optimization

Prof Brian Ripley ripley at stats.ox.ac.uk
Sun Apr 29 19:15:16 CEST 2007

```On Sun, 29 Apr 2007, fc502 at york.ac.uk wrote:

> hi everyone!
>
> i've got a problem in optimizing the following function
>
> fun <- function(theta){
> theta <- rbind(beta,lambda)
> fun <- sum(exp(h(beta)%*%lambda))
> fun
> }

Well, what are beta and lambda?  Trying to optimize a function that does
not depend on its argument is going to be difficult.

> where h(beta) is
>
> h <- function(beta,...){
> g1 <- matrix(0,b,M)
> g2 <- matrix(0,b,M)
> h1 <- matrix(0,b,1)
> h2 <- matrix(0,b,1)
> for(f in 1:M){
>  for(F in 1:b){
>   g1[F,f] <- exp(mu-beta*(z1[F,f]+z2[F,f])+3*z2[F,f])-1
>   g2[F,f] <- z2[F,f]*(exp(mu-beta*(z1[F,f]+z2[F,f])+3*z2[F,f])-1)
>  }
> }
> for(q in 1:b){
>  h1[q] <- (1/M)*sum(g1[q,])
>  h2[q] <- (1/M)*sum(g2[q,])
> }
> h <- matrix(0, b,2)
> h[,1] <- h1
> h[,2] <- h2
> h
> }
>
> i tried to optimize fun with optim and nlminb but i get an error:
> Error in beta * (z1[F, f] + z2[F, f]) :
>        non-numeric argument to binary operator

Possibly that the visible 'beta' is the R function of that name?

> and provide commented, minimal, self-contained, reproducible code.

It would have helped to have a complete example.  But using the debuggig