1

I already have several regression results, e.g. fit1, fit2, fit3. And I want to extract BIC from the regression result by using apply function.

Question is, when I code as follow:

fitresult = cbind(fit1, fit2, fit3)
BIC = apply(fitresult, 2, BIC)

It shows error:

Error in UseMethod("logLik") : no applicable method for 'logLik'
applied to an object of class "list"

I checked and find class(fitresult[1]) = 'list' and loglik cannot apply on 'list' class. I think this error means I cannot use BIC(fitresult[1]) because fitresult[1] is not a fit result object.

So how can I use apply function to make each component in fitresult applied by apply function? By changing the class of each component?

eipi10
  • 91,525
  • 24
  • 209
  • 285
Ericshaw
  • 51
  • 6
  • Please review how to create a [minimal reproducible example](https://stackoverflow.com/a/5963610/8386140) to help others help you. – duckmayr Nov 17 '17 at 23:53

1 Answers1

1

TL;DR: The cbind operation strips the model class (for example, class is lm if the model object was created with the lm function) from the model objects, but BIC expects an object with a model class (like lm or glm). Instead, do lapply(list(fit1, fit2, fit3), BIC) and BIC will work.


Assuming fit1, fit2, and fit3 are objects that resulted from running a modeling function (like lm or glm), then these are objects are lists containing the model output (for example, run str(fit1).

BIC is expecting a model object (for example, if the model was created with lm, the output object would be a list of class lm). However, the output of cbind(fit1, fit2, fit3) has class matrix, and each column contains all the sub-list elements from a given model object (for example, type fitresult, class(fitresult), fitresult[1, ], and fitresult[2, ] in the console and see what happens). However, these columns of fitresult no longer have the model class lm attached to them, so BIC doesn't know how to operate on them. For example, if you used lm to create the model then class(fit1) would return lm. But after the cbind operation. note that class(fitresult[ ,1]) returns list.

Instead, put these model objects into a list and use lapply to run BIC on each model object:

lapply(list(fit1, fit2, fit3), BIC)

The output should be a list where each element is the BIC from a given model. If you want the output as a vector, you can do:

sapply(list(fit1, fit2, fit3), BIC)
eipi10
  • 91,525
  • 24
  • 209
  • 285