Your function myfun
returns a vector of length 6 (because you multiply with xx$sex
). It needs to be of length 1. Also, the optim
function takes the par
first and the function as second parameter.
EDIT: You need to rewrite your function to return a single value. -exp(X'b)
is a vector of length of your observations. Maybe this goes in your direction:
myfun1 <- function(par, data) {
xx <- matrix(c(as.numeric(dat$sex), age, rep(1, nrow(dat))), ncol=3)
sum(-exp(xx %*% par))
}
optim(c(0.1,0.4,0.7), myfun1, data=dat)
Note that it would be more efficient to pass xx
to optim
since the calculation of xx
is independent of the iteration.