R Extract Log Likelihood from a plm object

937 views Asked by At

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)
1

There are 1 answers

1
Moritz Schwarz On BEST ANSWER

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.