Logit
<- function(x) {
inv_logit
<- 1 / (1 + exp(-x))
p return(p)
}
<- function(data, formula) {
logit
<- model.frame(formula, data, na.action=na.exclude)
mf <- model.response(mf, type="double")
Y <- model.matrix(formula, mf)
X
<- numeric(ncol(X))
b
<- function(b) {
logitll
<- inv_logit((X %*% b))
p <- Y*log(p) + (1-Y)*log(1-p)
lli
return(-sum(lli))
}
<- optim(b, logitll, method="BFGS")
est <- est$par
b names(b) <- colnames(X)
return(b)
}
Testing the function:
set.seed(42)
<- 1000
N <- rnorm(N)
X1 <- rnorm(N)
X2 <- 1.5 + 2*X1 + 3*X2 + rnorm(N)
ystar <- rbinom(N, 1, inv_logit(ystar))
y
<- data.frame(
df
y, X1, X2
)
<- y ~ X1 + X2
f
coef(glm(f,binomial,df))
## (Intercept) X1 X2
## 1.413335 1.839204 2.472301
logit(df, f)
## (Intercept) X1 X2
## 1.413368 1.839245 2.472373