For my thesis I have to fit some glm models with MLEs that R doesn't have, I was going ok for the models with close form but now I have to use de Gausian CDF, so i decide to fit a simple probit model. this is the code:
Data:
set.seed(123)
x <-matrix( rnorm(50,2,4),50,1)
m <- matrix(runif(50,2,4),50,1)
t <- matrix(rpois(50,0.5),50,1)
z <- (1+exp(-((x-mean(x)/sd(x)))))^-1 + runif(50)
y <- ifelse(z < 1.186228, 0, 1)
data1 <- as.data.frame(cbind(y,x,m,t))
myprobit <- function (formula, data) 
{
  mf <- model.frame(formula, data)
  y <- model.response(mf, "numeric")
  X <- model.matrix(formula, data = data)
  if (any(is.na(cbind(y, X)))) 
    stop("Some data are missing.")
  loglik <- function(betas, X, y, sigma) {     #loglikelihood
    p <- length(betas)
    beta <- betas[-p]
    eta <- X %*% beta
    sigma <- 1    #because of identification, sigma must be equal to 1
    G <- pnorm(y, mean = eta,sd=sigma)
    sum( y*log(G) + (1-y)*log(1-G))
  }
  ls.reg <- lm(y ~ X - 1)#starting values using ols, indicating that this model already has a constant
  start <- coef(ls.reg)
  fit <- optim(start, loglik, X = X, y = y, control = list(fnscale = -1), method = "BFGS", hessian = TRUE) #optimizar
  if (fit$convergence > 0) {
    print(fit)
    stop("optim failed to converge!") #verify convergence
  }
  return(fit)
}
myprobit(y ~ x + m + t,data = data1)
And i get:  Error in X %*% beta : non-conformable arguments, if i change start <- coef(ls.reg) with start <- c(coef(ls.reg), 1) i get wrong stimatives comparing with:
probit <- glm(y ~ x + m + t,data = data1 , family = binomial(link = "probit"))
What am I doing wrong? Is possible to correctly fit this model using pnorm, if no, what algorithm should I use to approximate de gausian CDF. Thanks!!
 
     
     
    