rm(list=ls()) ## ## Warmup ## ## 1. ## calculating from first principles choose(10,3) * 0.5^3 * (1-0.5)^7 ## or using the dbinom command dbinom(3, size=10, prob=0.5) ## 2. dbinom(10, size=20, prob=0.512) ## 3. barplot(dbinom(0:6, size=6, prob=0.512), space=0, col='red', main='', las=1, xlab='Number of boys', ylab='Probability') axis(side=1, at=0:6+0.5, labels=0:6) ## 4. dgeom(10, prob=0.1) ## 5. sum(dgeom(0:5, prob=0.1)) ## 6. dexp(2, rate=1/0.5) ## note that the 'rate' argument is actually the ## mean of the exponential, which is 1/rate, as we ## might interpret it ## 7. ## create function to plot f <- function(x) dexp(x, rate=1/0.5) ## plot curve curve(f, from=0, to=5, xlab='Search time', ylab='Probability', las=1) ## ## Illegal tender ## ## 1. vals <- seq(from=0.01, to=0.99, by=0.01) ## 2. ## ## for a single value (e.g., 0.05), the log-likelihood would be ## calculated as dbinom(46, 50, prob=0.05, log=TRUE) ## ## and now, all at once likelihoods <- dbinom(46, 50, prob=vals, log=TRUE) ## 3. plot(x=vals, y=likelihoods, type='l', las=1, xlab=expression(italic(p)), ylab='Log-likelihood') ## 4. vals <- seq(from=0.85, to=0.95, length=100) likelihoods <- dbinom(46, 50, prob=vals, log=TRUE) plot(x=vals, y=likelihoods, type='l', las=1, xlab=expression(italic(p)), ylab='Log-likelihood') ## 5. mle <- vals[which.max(likelihoods)] mle abline(v=mle, col='red', lty=2) ## or, using 'optimize' f.loglik <- function(x) dbinom(46, 50, prob=x, log=TRUE) optimize(f.loglik, interval=c(0, 1), maximum=TRUE)$maximum ## 6. ## critical value (change the 0.05 if you wanted something other than ## 95% confidence interval) ## ## need to re-create vals, because the narrow-range one above might ## not be wide enough. Let's try 10^5 values here, so that we get ## something quite accurate vals <- seq(from=0, to=1, length=10^5) likelihoods <- dbinom(46, 50, prob=vals, log=TRUE) chi.2 <- qchisq(0.05, df=1, lower.tail=FALSE)/2 vals.above <- vals[(max(likelihoods)-likelihoods (max(likelihoods)-chi.2)) ci.v1 <- range(rates[keep]) ## option 2: using R's uniroot function ## ## first, create a new function which is our likelihood function ## shifted so that the max is zero, and then up by 1.92 - the roots of ## this function are our 95% CI f.loglik.shifted <- function(x) f.loglik(x)-f.loglik(mle)+chi.2 ## find the roots f.max.lower.ci <- uniroot(f.loglik.shifted, lower=0, upper=mle)$root f.max.upper.ci <- uniroot(f.loglik.shifted, lower=mle, upper=0.2)$root ci.v2 <- c(f.max.lower.ci, f.max.upper.ci) ## add lines for 95% CI plot.ll() abline(v=ci.v2, lty=2, col='blue') ## 5. ## mle: 1/0.036 ## 95% CI: rev(1/c(0.025, 0.05)) ## rev puts CI in a sensible order