简体   繁体   中英

How to calculate AIC and BIC in a loop?

I have 10 different models for the same dataset and I want to compare both the AIC and the BIC for all models.

I thought of creating a character vector called models with the models's names:

modelsnames = c("model1", "model2",...,"model10")

Then, I wanted to calculate both those statistics in the following way:

for ( i in 1:length(models)){
Akaike[i] = AIC(models[i],k = 2)
BIC[i] = BIC(models[i])
}

But I get this error:

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

It became clear (or at least, it appears so) that I can call neither AIC nor BIC using a character as argument.

How can I efficiently calculate the AIC and BIC for my models and store the answer into one array? For 10 models, it's quickly doable by means of copying, pasting, and making minor changes, but once the number of models goes up, it becomes quite cumbersome.

All help will be appreciated.

Obs.: I also tried to creat an array with 10 position, in which each position would be linked to one of my models, but I also couldn't do it. That's why I created vector modelnames by hand.

Replace models[i] with get(models[i]) .

Most functions work on data, not on names. With get , R looks in the current environment and tries to find the element with that name according to the usual rules.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM