Solved – Likelihood ratio test in R

likelihood-ratiorself-study

I am in desperate need for help. I am trying to calculate the likehood ratio test in R, but I don't have allot of experience using R.

For example, to calculate the following

Suppose $X_1, X_2,\ldots, X_n$ is a random sample from a normal population with mean $\mu$ and variance $16$. Find the test with the best critical region, that is, find the most powerful test, with a sample size of $n = 16$ and a significance level $\alpha = 0.05$ to test the simple null hypothesis $H_0: \mu = 10$ against the simple alternative hypothesis $H_A: \mu = 15$.

This is the code I have up until now

#X values
#Added the mean=10 thanks to the comments here
X=rnorm(16,10,sd=4)

mlog1=function(media,x,sdev){
sum(-dnorm(x,mean=media, sd=sdev, log=T))
}

#L(10)
#also added sdev
out1=nlm(mlog1,10,x=X,sdev=4)
#L(15)
#also added sdev
out2=nlm(mlog1,15,x=X,sdev=4)

k1=out1$estimate
    k2=out2$estimate

#L(10)/L(15)    
print( k1/k2)

This is the very basic axample and the solution, done by hand, can be found here.

I know you also have the LRT function, but I don't know how to apply this function.

Please help, the code looks correct but it always returns 1 or 0.9999999 for any value in the parameters.

Best Answer

In addition to @Henry's answer and to @PeterEllis' comment, here are a few comments about the R code itself:

  • The third argument of mlog1 is sdev. You therefore need sdev in out1 and out2 (not sd);
  • The likelihood ratio test is the logarithm of the ratio between two likelihoods (up to a multiplicative factor). Equivalently, it is a difference between two log-likelihoods (up to a multiplicative factor). It is not the ratio between two log-likelihoods.
  • k1=out1$estimate returns an estimate of $\mu$. k2=out2$estimate returns another estimate of $\mu$ (based on another starting value). Both aim to estimate the same thing; that's why you always get something very close to $1$. Neither of them returns minus a log-likelihood.
  • You forgot the multiplicative factor ($-2$).
Related Question