I'm trying to maximize the log-likelihood $y_1 \log(p_1) + (1-y_1)\log(p_1) + y_2\log(p_2) + (1-y_2)\log(p_2)$. I have data on success of an experiment. Y identifies if person died or not, and X identifies control or treatment group.
What's wrong with my code?
# MLE for the likelihood
y <- c(rep(1,39), rep(0,674-39), rep(1,22), rep(0,680-22))
x <- c(rep(0, 674), rep(1, 680))
binom.ll <- function(theta, y, x) {
y[x==0]*log(theta[1]) + (1-y[x==0])*log(1-theta[1])) + y[x==1]*log(theta[2]) + (1-y[x==1])*log(1-theta[2]))
}
theta.start <- c(0, 0)
ml.res <- nlm(binom.ll, theta.start, print.level=1, y=y, x=x, hessian=T)
ml.res
iteration = 0
Step:
[1] 0 0
Parameter:
[1] 0 0
Function Value
[1] 1.797693e+308
Gradient:
[1] -Inf 0
Error in nlm(binom.ll, theta.start, print.level = 1, y = y, x = x, hessian = T): non-finite value supplied by 'nlm'
In addition: Warning messages:
1: In nlm(binom.ll, theta.start, print.level = 1, y = y, x = x, hessian = T): NA/Inf replaced by maximum positive value
2: In nlm(binom.ll, theta.start, print.level = 1, y = y, x = x, hessian = T): NA/Inf replaced by maximum positive value
binom.ll
return a scalar? Right now it is trying to add vectors of different lengths (and you have mismatching parenthesis in multiple places). Also note thatlog(0)
is not finite so you might want to start at(0.5, 0.5)
. $\endgroup$nlm
does a minimization so you'll have to negate your objective function. $\endgroup$x*theta
and(1-x)*(1-theta)
. I would recommend moving this to stats.stackexchange to get some advice on algorithms to evaluate experiments of this sort. Meanwhile, have you looked at alternative approaches, such as stackoverflow.com/questions/8085361/… ? $\endgroup$