title: How to solve a simple optimization in R
body: <p>I am trying to use the optim() function in R to solve a simple problem, but I am facing some problems on how to implement it:</p>
  
  <pre><code> e=tot_obs/(sum(Var1)+sum(Var2)+sum(Var3)+sum(Var4))
   output=(Var1+Var2+Var3+Var4)*e
  </code></pre>
  
  <p>I know the total of the observations and all the variables.</p>
  
  <pre><code># Fake datasets   
  # Considering that this are the observations c(1000,250,78,0,0,90)
  
  #Known data
  total_observations=1418
  var1=c(1,0.3,0.5,0.01,0.05,0.6)
  var2=c(500,40,40,0,0,100)
  var3=c(1,0.1,0.2,0,0.1,0)
  var4=c(2,0.04,0.003,0.003,0,0.05)
  
  #Function
  e=total_observations/(sum(var1)+sum(var2)+sum(var3)+sum(var4))
  output=(var1+var2+var3+var4)*e
  </code></pre>
  
  <p>I can do a simple correlation between observations and output, with good results (~0.90). This one gives me 0.97.</p>
  
  <p>But now I want to test the effect of having different weights assign to each variable.</p>
  
  <pre><code>e=tot_obs/(sum(w1*Var1)+sum(w2*Var2)+sum(w3*Var3)+sum(w4*Var4))
  output=(w1*Var1+w2*Var2+w3*Var3+w4*Var4)*e
  where w1+w2+w3+w4=1
  and cor(observations,output)~1
  </code></pre>
  
  <p>I was trying to use optim() function, however I am completely lost. If anyone could help me out or point me some good references on how to do this, I would appreciate.</p>