Reputation: 231
Suppose I have a data set. There are some categorical variables and some numerical variables. I want to estimate the parameters of a model e^{X'b}
for every categories and others. I am trying to do it in R code. I need to do it by creating design matrix for categorical variables like age==2
and age==3
, where considering age==1
as reference category. But this program is not running and giving errors. What is the problem?
sex <- c("F","M","F","M","F","M")
age <- c(1,3,2,3,1,2) # categorical variable with three age categories
age <- as.factor(age)
dat <- data.frame(sex,age)
myfun <- function(par, data){
xx <- data
func <- exp(par[1]*(xx$age==2)+par[2]*(xx$age==3)+par[3]*factor(xx$sex))
return(-func)
}
optim(myfun, par=c(0.1,0.4,0.7), data=dat)
Upvotes: 0
Views: 898
Reputation: 18420
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.
Upvotes: 2