将函数参数传递给mle()以获取对数似然

我正在使用mle()方法在R中手动估计具有多个预测变量的logit回归.我无法在下面的函数calcLogLikelihood中传递计算对数似然性所需的其他参数.

这是我计算负对数似然的函数.

calcLogLikelihood <- function(betas, x, y) { 
# Computes the negative log-likelihood 
#   
# Args: 
#   x: a matrix of the predictor variables in the logit model 
#   y: a vector of the outcome variable (e.g. living in SF, etc)
#   betas: a vector of beta coefficients used in the logit model 
#  
# Return: 
#   llf: the negative log-likelihood value (to be minimized via MLE)
# 
# Error handling: 
# Check if any values are null, and whether there are same number of coefficients as there are  predictors
  if (TRUE %in% is.na(x) || TRUE %in% is.na(y)) {
    stop(" There is one or more NA value in x and y!")
  }
  nbetas <- sapply(betas, length)
  if (nbetas-1 != ncol(x)) {
     print(c(length(betas)-1, length(x)))
     stop(" Categorical vector and coef vector of different lengths!")
   }
  linsum <- betas$betas[1] + sum(betas$betas[2:nbetas] * x)
  p <- CalcInvlogit(linsum)
  llf <- -1 * sum(data$indweight * (y * log(p) + (1-y) * log(1-p)))
  return(llf)

}

这是我的x和y数据矩阵的样子:

> head(x)
  agebucket_(0,15] agebucket_(15,30] agebucket_(30,45] agebucket_(45,60] agebucket_(60,75]
1                0                 0                 1                 0                 0
2                0                 0                 1                 0                 0
3                0                 0                 1                 0                 0
4                0                 0                 1                 0                 0
5                0                 0                 1                 0                 0    
6                0                 0                 0                 1                 0

> head(y)
 [,1]
[1,]    1
[2,]    1
[3,]    0
[4,]    0
[5,]    1
[6,]    0

这是对我的功能的调用:

# Read in data
data <- read.csv("data.csv")   

# cont.x.vars and dummy.x.vars are arrays of predictor variable column names
x.vars <- c(cont.x.vars, dummy.x.vars)

# Select y column. This is the dependent variable name.
y.var <- "Housing"

# Select beta starting values
betas <- list("betas"=c(100, rep(.1, length(x.vars))))

# Select columns from the original dataframe
x <- data.matrix(data[, x.vars])
y <- data.matrix(data[, y.var])

# Minimize LLF
fit <- mle(calcLogLikelihood, betas, x=x, y=y)

这是我的错误消息:

 Error in is.na(x) : 'x' is missing 

这个错误似乎即将到来,因为我没有正确传递calcLogLikelihood所需的x和y参数,但我不确定出了什么问题.我该如何解决这个错误?

最佳答案 出现错误是因为函数stats4 :: mle没有使用省略似然函数的省略号参数传递任何参数.相反,省略号用于将更多参数传递给optim(参见?stats4 :: mle).您必须注意您的似然函数只是要优化的参数的函数.数据,即x和y,不能在调用mle时传递.

你有两个选择. 1.重新定义你的可能性函数.您可以依赖R的词法范围规则,因为您将数据(x,y)视为自由变量(只需从函数定义中删除参数x和y并在工作空间中定义x和y),或者定义闭包明确哪个是一个更强大的解决方案并解释(例如)here.2.你也可以使用optim而不是mle,它允许你保持你的可能性定义,并被mle用作后台的优化器.

点赞