| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 
 | 
 
 
 
 
 
 
 
 
 num.stems <- c(6,8,9,6,6,2,5,3,1,4)
 aphids_count <- c(0,1,2,3,4,5,6,7,8,9)
 aphids <- data.frame(aphids_count, num.stems)
 
 
 aphids_raw <- rep(aphids_count, num.stems)
 
 
 
 
 
 
 
 nnominb.loglik <- function(p) {
 res <- sum(log(dnbinom(aphids_raw, mu = p[1], size = p[2])))
 return(res)
 }
 
 
 
 neg.nnominb.loglik <- function(p) {
 res <- sum(log(dnbinom(aphids_raw, mu = p[1], size = p[2])))
 return(-res)
 
 }
 
 
 
 
 
 
 out.NB <- nlm(neg.nnominb.loglik, c(4,4))
 
 out.NB
 
 
 
 
 
 
 
 
 x <- seq(0.1, 10, by = 0.1)
 
 
 y_max <- sapply(x, function(x) nnominb.loglik(p = c(out.NB$estimate[1], x)))
 plot(y_max ~ x, type = "l", ylab = "Log Likelihood", xlab = "Size")
 
 
 y_2 <- sapply(x, function(x) nnominb.loglik(p = c(2, x)))
 lines(y_2 ~ x, col = 2)
 
 
 y_5 <- sapply(x, function(x) nnominb.loglik(p = c(5, x)))
 lines(y_5 ~ x, col = 3)
 
 
 legend('bottomright', c(expression(mu=='MLE (3.46)'),
 expression(mu==2), expression(mu==5)),
 col=c(1,2,3), lty=c(1,1,1), cex=.9, bty='n')
 
 
 
 
 
 
 
 
 image(seq(2,5,.1), seq(1,4,.1), z.matrix, col = cm.colors(30),
 xlab = expression(mu), ylab = "Number of Trials")
 
 contour(seq(2,5,.1), seq(1,4,.1), z.matrix, add = TRUE)
 
 points(x = out.NB$estimate[1], y = out.NB$estimate[2], pch = 3)
 
 
 
 
 
 
 
 
 grids <- expand.grid(mu=seq(2,5,.1), theta=seq(1,4,.1))
 
 grids$z <- apply(grids, 1, function(x) nnominb.loglik(p = c(x[1], x[2])))
 
 z.matrix <- matrix(grids$z, nrow=length(seq(2,5,.1)))
 
 
 
 
 persp(seq(2,5,.1), seq(1,4,.1), z.matrix,
 xlab=expression(mu), ylab=expression(theta), zlab='Log Likelihood',
 ticktype='detailed', theta=30, phi=20, d = 4)
 
 
 
 library(lattice)
 wireframe(z~mu*theta, data=grids, xlab=expression(mu),
 ylab=expression(theta), zlab="Log-nlikelihood",
 scales = list(arrows = FALSE), drape=TRUE,
 par.settings=list(par.zlab.text=list(cex=.75),
 axis.text=list(cex=.75)))
 
 
 |