# MLE with optim(), error in "gradient in optim evaluated to length 1 not 3"

I do a poisson regression with the optim function. I calculatetd the gradient of the loglikelihood and try to pass it as an argument to the optim function and as a result i get an error. ""gradient in optim evaluated to length 1 not 3" Where is my mistake? (Sorry for the german comments)

``````# Funktion zur Berechnung der LogLikelihood
logLikePois <- function(y, x, parameter) {

# Anzahl der zu sch?tzenden Koeffizienten
betaKoef <- parameter

# Lamba der Poissonregression
lambda <- exp(betaKoef %*% t(x))

# Negative Loglikelihood bassiend aus Lambda. Negativ, da die optim Funktion
# nur minimiert und die  Likelihood aber maximiert werden soll
logLikeliHood <- sum(-lambda+y*log(lambda)-log(factorial(y)))
return(logLikeliHood)

}
betaKoef <- parameter

# Lamba der Poissonregression
lambda <- exp(betaKoef%*%t(x))
}

# Ausgeben der Loglikelihood

data(discoveries)
disc <- data.frame(count=as.numeric(discoveries),
year=seq(0,(length(discoveries)-1),1))

yearSqr <- disc\$year^2

formula <- count~year+yearSqr

form <- formula(formula)

# DataFrame wird erzeugt
model <- model.frame(formula, data = disc)

#  Designmatrix wird erzeugt
x <- model.matrix(formula, data = disc)

# Response Variable erzeugt
y <- model.response(model)

parFullModell <- c(1,0,0)

optimierung <- optim(par =  parFullModell, fn = logLikePois,
x = x, y = y,gr=grad ,method = "BFGS", hessian = TRUE)
``````