Note that there are some explanatory texts on larger screens.

plurals
  1. PO'optimize' not finding variables inside a function call
    text
    copied!<p>I have the following function that draws some data from a chi-squared distribution and compares the distribution of X to a known chi-squared distribution using maximum likelihood. This procedure is simulated <code>nSims</code> times. (I compare these results to results from a permutation test, but that code is excluded.)</p> <pre><code>chi2c &lt;- function(xdf=2, yObs=100, xObs=100, nSims=1000, nPerm=500, alpha=0.05){ simResults &lt;- sapply(1:nSims, function(x){ # Draw variables x &lt;- rchisq(xObs, df=xdf) # Other variables not relevant here # [[snip]] # Permutation test # [[snip]] # Calculate the statistics necessary for maximum likelihood n &lt;&lt;- length(x) sumlx &lt;&lt;- sum(log(x)) sumx &lt;&lt;- sum(x) # Calculate the maximum likelihood estimate dfhat &lt;- optimize(f=c2ll, interval=c(1, 10), maximum=TRUE)$maximum # Calculate the test statistic: -2 times the log likelihood ratio llr &lt;- -2 * (c2ll(2) - c2ll(dfhat)) # Compare the test statistic to its asymptotic dist: chi-squared lReject &lt;- llr &gt; qchisq(1 - alpha, df=1) # Provide the results # [[snip]] }) # Calcuate means across simulations rowMeans(simResults) } </code></pre> <p>This function calls <code>c2ll</code>, the chi-squared likelihood function</p> <pre><code>c2ll &lt;- function(dfHat){ -n * log(gamma(dfHat/2)) - n * (dfHat/2) * log(2) + (dfHat/2 - 1) * sumlx - sumx/2 } </code></pre> <p>This function does just what I would like and is accurate, but I don't understand why I have to set the maximum likelihood statistics (<code>n</code>, <code>sumlx</code>, and <code>sumx</code>) globally to get it to work; <code>optimize</code> doesn't find them if I only set them inside the function using <code>&lt;-</code>. I tried setting them inside of <code>optimize</code>, but that didn't work either. Thanks for your help.</p> <p>Charlie</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