title: optimize a function in r ( Error in solve.default)
body: <p>I have the following equation:</p>
  
  <p><a href="https://i.stack.imgur.com/5F4I8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5F4I8.jpg" alt="enter image description here"></a>  (1)</p>
  
  <p><code>Rp,t+1</code>= the return of the portfolio .. <code>fr</code> = free risk rate.. <code>rt+1</code>: the return of a strategy.
  <code>beta</code> has the following expression:<br>
  <code>beta=x0+x1*A+ x2*B+ x3*C+x4*D</code>  (Estimated using Generalized Method of Moments (GMM) (1).<br>
  <code>A</code>,<code>B</code>,<code>C</code> and <code>D</code> are the risk factors related to <code>rt+1</code>.</p>
  
  <p>My objective is to find the optimal values of <code>x1</code>, <code>x2</code>, <code>x3</code> and <code>x4</code> that maximize the utility function of the investor.  </p>
  
  <p><a href="https://i.stack.imgur.com/c9xdn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c9xdn.png" alt="enter image description here"></a></p>
  
  <p>with <code>U(Rp,t+1;x)</code> is the investor utility<br>
  <code>x</code> is the vector of parameters to maximize<br>
  <code>Zt</code> presents the 4 risk factors.   </p>
  
  <p>The code is:</p>
  
  <pre><code>ret&lt;-cbind(ret)  #ret= rt+1
  factors&lt;-cbind(A,B,C,D)
  
  func&lt;-function(x,ret,factors) {
  df &lt;- data.frame(A=factors$A*x[1],B=factors$B*x[2],C=factors$C*x[3], D=factors$D*x[4])
  H&lt;-as.matrix(factors)
  HH&lt;-matrix(H,179,4)
  m &lt;- gmm(ret~., data=df, HH)
  b&lt;- coef(m)
  beta&lt;- b[1]+b[2]*factors$A+b[3]*factors$B+b[4]*factors$C+b[5]*D
  beta=cbind(beta)
  
  r=RF+beta*ret  #equation (1)
  #Annual Sharpe ratio of the portfolio
  averp&lt;-mean(r)*12 
  sigmap&lt;-sqrt(12)*sd(r)
  Sharpe&lt;-averp/sigmap
  
  #Calculating utility
  u&lt;-1/nrow(r)*sum((1+r)^(1-5)/(1-5))
  obj&lt;-u
  result &lt;- list(obj=obj,u=u,beta=beta,r=r,averp=averp,sigmap=sigmap,Sharpe=Sharpe)
  return(result)
  }
  
  #Catching the obj from the function    
  Final&lt;-function(x,ret,factors){
  bra&lt;-func(x,ret,factors)
  #print(bra$obj)
  return(-bra$obj)
  }
  p&lt;-optim(par = c(0,1,2,3),Final,method="Nelder-Mead",ret=ret,factors=factors)
  bra&lt;-func(x=p$par,ret=ret,factors=factors)
  </code></pre>
  
  <p>When I run the code, I get the following errors:
   for p --> </p>
  
  <pre><code>Error in solve.default(crossprod(hm, xm), crossprod(hm, ym)) : 
    Lapack routine dgesv: system is exactly singular: U[2,2] = 0 
  </code></pre>
  
  <p>for bra --> </p>
  
  <pre><code>Error in is.data.frame(x) : 
    (list) object cannot be coerced to type 'double' 
  </code></pre>
  
  <p>I am would be veryy grateful if you could help me on this ! Thank you </p>