title: Error during evaluation of expression in optim()
body: <p>I'm implementing a function in R for finding the parameters that minimize the quadratic error for an arbitrary pdf function (e.g., pnorm, punif, pbinom, etc.). The design is such that the user provides probabilities, empirical quantiles, a function name (<code>densit</code>), and a list of parameter names (<code>params</code>) from the <code>densit</code> function (e.g., <code>mean</code> and <code>sd</code> in <code>pnorm</code>). For instances, being for <code>q1</code>, <code>q2</code>, and <code>q3</code> equal to -1.644854, 0, and 1.644854, and <code>p1</code>, <code>p2</code>, and <code>p3</code> equal to 0.05, 0.5, 0.95, the function should recover <code>mean</code> and <code>sd</code> as approximately 0 and 1 respectively.</p>
  
  <p>The goal is to feed such expression to <code>optim</code>, so that the latter takes a function (called internally <code>quadraticFun</code>) that should evaluate an expression during optimization; however, I can't make <code>optim</code> work on such expression for estimation. The function is this: </p>
  
  <pre><code>fun  &lt;- function(p1 = 0.05, p2 = 0.50, p3 = 0.95, q1, q2, q3, output = "complete", densit, params) {
      densit &lt;- substitute(densit)
      params &lt;- sapply(params, as.name)
      densiCall1 &lt;- as.call(c(as.list(densit), as.list(q1), params))
      densiCall2 &lt;- as.call(c(as.list(densit), as.list(q2), params))
      densiCall3 &lt;- as.call(c(as.list(densit), as.list(q3), params))
      quadratEq &lt;- substitute((densiCall1 - p1)^2 +
                              (densiCall2 - p2)^2 +
                              (densiCall3 - p3)^2)
      quadraticFun &lt;- function(params) {
          eval(quadratEq)
      }    
      initVals &lt;- rep(1, times = length(params))
      res &lt;- optim(initVals, quadraticFun) # ERROR SOMEWHERE AROUND HERE...
      # if output is set to "complete", return the whole res object, otherwise, return just the parameters 
      if (output == "parameters") {
          return(res$par)
      }
      return(res)
  }
  </code></pre>
  
  <p>Debugging with the next example indicates that the error shows up during the call <code>optim(initVals, quadraticFun)</code>, specifically during evaluation of <code>quadraticFun</code> with the following message:</p>
  
  <pre><code>&gt; findParams(q1 = -1.644854, q2 = 0, q3 = 1.644854, densit = pnorm, params = list("mean", "sd"))
  Error in pnorm(-1.644854, mean, sd) : 
    Non-numeric argument to mathematical function
  </code></pre>
  
  <p>It seems that the expression resulting is taken literally by the interpreter, i.e., <code>mean</code> and <code>as</code> as symbols to evaluate instead of arguments in the function to optimize.</p>
  
  <p>Thanks in advance for any hint that helps to solve this problem.</p>