Creating function arguments from a named list (with an application to stats4::mle)

后端 未结 4 1356
难免孤独
难免孤独 2021-02-06 02:20

I should start by saying what I\'m trying to do: I want to use the mle function without having to re-write my log likelihood function each time I want to try a different model s

4条回答
  •  暖寄归人
    2021-02-06 02:49

    You can use the mle2 function from the package bbmle which allows you to pass vectors as parameters. Here is some sample code.

    # REDEFINE LOG LIKELIHOOD
    ll2 = function(params){
      beta = matrix(NA, nrow = length(params) - 1, ncol = 1)
      beta[,1] = params[-length(params)] 
      sigma    = params[[length(params)]]
      minusll  = -sum(log(dnorm(Y - X %*% beta, 0, sigma)))
      return(minusll)
    }
    
    # REGRESS Y ON X1
    X <- model.matrix(lm(y ~ x1, data = df))
    mle2(ll2, start = c(beta0 = 0.1, beta1 = 0.2, sigma = 1), 
      vecpar = TRUE, parnames = c('beta0', 'beta1', 'sigma'))
    
    # REGRESS Y ON X1 + X2
    
    X <- model.matrix(lm(y ~ x1 + x2, data = df))
    mle2(ll2, start = c(beta0 = 0.1, beta1 = 0.2, beta2 = 0.1, sigma = 1), 
          vecpar = TRUE, parnames = c('beta0', 'beta1', 'beta2', 'sigma'))
    

    This gives you

    Call:
    mle2(minuslogl = ll2, start = c(beta0 = 0.1, beta1 = 0.2, beta2 = 0.1, 
        sigma = 1), vecpar = TRUE, parnames = c("beta0", "beta1", 
        "beta2", "sigma"))
    
    Coefficients:
         beta0      beta1      beta2      sigma 
     0.5526946 -0.2374106  0.1277266  0.2861055
    

提交回复
热议问题