mle() メソッドを使用して、R で手動で複数の予測変数を使用してロジット回帰を推定しています。以下の関数で対数尤度を計算するために必要な追加の引数を渡すのに問題があり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
このエラーは、必要な x パラメーターと y パラメーターをcalcLogLikelihood
正しく渡していないために発生しているようですが、何が問題なのかわかりません。このエラーを修正するにはどうすればよいですか?