Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>R has lexical scoping, which means that functions look for variables in the environment in which they were defined. c2ll is defined in the global environment, so it doesn't see your definitions of n, sumx, and sum1x inside the function. S on the other hand uses dynamic scoping, which behaves as <em>you</em> expect (i.e. it looks for variables in the scope in which it was called). Computer scientists generally believe that dynamic scoping was a dead-end bad idea, and that lexical scoping is the way to go.</p> <p><strong>As a practical matter, what can you do about this?</strong></p> <p>Well, there are a couple options...</p> <p><strong>First</strong>, you can define your function locally:</p> <pre><code>n &lt;- length(x) sumlx &lt;- sum(log(x)) sumx &lt;- sum(x) c2ll &lt;- function(dfHat){ -n * log(gamma(dfHat/2)) - n * (dfHat/2) * log(2) + (dfHat/2 - 1) * sumlx - sumx/2 } dfhat &lt;- optimize(f=c2ll, interval=c(1, 10), maximum=TRUE)$maximum </code></pre> <p><strong>Second</strong>, you can have c2ll take additional parameters, and pass those parameters through optimize.</p> <pre><code>#in global env c2ll &lt;- function(dfHat,n,sum1x,sumx){ -n * log(gamma(dfHat/2)) - n * (dfHat/2) * log(2) + (dfHat/2 - 1) * sumlx - sumx/2 } #... #in function n &lt;- length(x) sumlx &lt;- sum(log(x)) sumx &lt;- sum(x) dfhat &lt;- optimize(f=c2ll, interval=c(1, 10), n=n,sum1x=sum1x,sumx=sumx, maximum=TRUE)$maximum </code></pre> <p>Both are clean options that preserve the encapsulation of your functions.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload