R demos

Back to all R demos
Likelihood and MLE
You can try out the functions I used in lectures 6 and 7 to visualise (1) the binomial likelihood, and (2) the mle for the parameters of a normal distribution from a simulated simple random sample.
  1. Download this file: likelihood.R to your computer, and save it (as likelihood.R)
  2. Start up R
  3. In R, using the Source R code command (on the File menu), navigate to the appropriate folder, and select the file likelihood.R
  4. Run the demonstrations by typing either binomial.lik() or normal.lik()
  5. You can exit either function by clicking with the mouse below the horizontal axis of the plot.
  6. For binomial.lik():
    • The full syntax for the function is
      binomial.lik(X=45,K=100,thr=(4:36)/40,pmax=1.15*max(dbinom(X,n,thr)))
      with the interpretation that the observation X is treated as 1 observation from Binomial(K,theta). The parameter thr specifies the range of theta's considered, and pmax determines the vertical scaling of the figure. The values given above are the defaults, that can be overridden, e.g. you can type:
      binomial.lik()
      binomial.lik(23)
      binomial.lik(X=4,K=20)
    • Click with the mouse to the left of the vertical line representing the observed X to decrease theta, to the right to increase theta. The binomial probability mass function is re-plotted, and the red dot indicates the value of the likelihood, which rises or falls with theta. Note that the likelihood is maximised by theta=X/K (see notes).
  7. For normal.lik():
      The full syntax for the function is
      normal.lik(n=100,mu0=2.3,sigma0=1.4)
      meaning that a sample of size n is drawn from the Normal distribution with the specified parameters mu0 and sigma0. The values given above are the defaults, that can be overridden, e.g. you can type:
      normal.lik()
      normal.lik(n=250)
    • Click with the mouse anywhere in the main part of the figure to draw a fresh simulated sample, and re-plot the log-likelihood.