I have to start with what I'm trying to do: I want to use the mle function without rewriting my likelihood function every time I want to try a different model specification. Since mle expects a named list of initial values, you apparently cannot just write a log-likelihood function as a transfer of the parameter vector. A simple example:
Suppose I want to fit a linear regression model using maximum likelihood, and first I ignore one of my predictors:
n <- 100 df <- data.frame(x1 = runif(n), x2 = runif(n), y = runif(n)) Y <- df$y X <- model.matrix(lm(y ~ x1, data = df))
Now, if I want to customize another model, say:
m <- lm(y ~ x1 + x2, data = df)
I cannot reuse the log-likelihood function - I had to rewrite it to have beta3 parameter. What I would like to do is something like:
ll.flex <- function(theta){
if I could somehow adjust the initial argument in mle to account for my now logarithmic likelihood function with a vector input or banning what has a function that builds a logarithmic likelihood function at runtime, say by building a named argument list, and then using it to define a function, for example, something like this:
X <- model.matrix(lm(y ~ x1 + x2, data = df)) arguments <- rep(NA, dim(X)[2]) names(arguments) <- colnames(X) ll.magic <- function(bring.this.to.life.as.function.arguments(arguments)){...}
Update:
I ended up writing a helper function that can add an arbitrary number of named arguments x1, x2, x3 ... to the passed function f.
add.arguments <- function(f,n){ # adds n arguments to a function f; returns that new function t = paste("arg <- alist(", paste(sapply(1:n, function(i) paste("x",i, "=",sep="")), collapse=","), ")", sep="") formals(f) <- eval(parse(text=t)) f }
This is ugly, but he did his job, allowing me to reuse the log likelihood function on the fly.