R Extract Log Likelihood from a plm object
Asked Answered
A

1

2

I would like to extract the log likelihood from a plm object.

It works fine when using the logLik function from the base stats package with either felm from the lfe package or feols from the fixest package, but not with any plm object where the resulting error message is:

Error in UseMethod("logLik") : 
  no applicable method for 'logLik' applied to an object of class "c('plm', 'panelmodel')"

I checked and plm is not a class that is defined for in the stats package (see stats:::).

Am I missing something conceptually (aware that it's a ML estimation)? As in, why does lfe and fixest make it work and plm does not? Is there a workaround?

Thanks!

library(plm)
library(lfe)
library(fixest)
data("Produc", package = "plm")

# lfe
xx <- felm(log(gsp) ~ log(pcap) + log(pc) + log(emp) + unemp| state + year|0|0,data = Produc)
summary(xx)
logLik(xx)

# fixest
yy <- feols(log(gsp) ~ log(pcap) + log(pc) + log(emp) + unemp| state + year,data = Produc)
summary(yy)
logLik(yy)

# PLM
zz <- plm(log(gsp) ~ log(pcap) + log(pc) + log(emp) + unemp,data = Produc, index = c("state","year"))
summary(zz)
logLik(zz)
Aeolipile answered 3/10, 2020 at 15:19 Comment(1)
A method ´logLik.plm` is simply not defined in the plm package. Quite a variaty of panel models are of class "plm" so if one wants to implement a proper version, one would need to be careful (e.g., error gracefully for non-suitable/not yet implemented models if the logLik needs to calculated in different ways for different models).Reames
A
1

I think I figured it out:

object here is a plm object, like zz above.

logLik.plm <- function(object){
  out <- -plm::nobs(object) * log(2 * var(object$residuals) * pi)/2 - deviance(object)/(2 * var(object$residuals))
  
  attr(out,"df") <- nobs(object) - object$df.residual
  attr(out,"nobs") <- plm::nobs(summary(object))
  return(out)
}

This should then also work with the AIC command.

I have created a public gist here.

Aeolipile answered 13/12, 2020 at 18:4 Comment(1)
nobs and deviance should work directly on a plm object. Maybe by coincidence, it also works on the associated summary object but that is the less efficient approach.Reames

© 2022 - 2024 — McMap. All rights reserved.