0

I am using the relaimpo package to obtain the relative importances of variables in a linear model. The function calc.relimp() calculates relative importances using several possible methods. I would like to compare the results from using each method on a dataset I am working with.

The calc.relimp() function returns an S4 object. In order to access the list of relative importances alone, I save the output of the function to a variable name like rel.imp <- calc.relimp(blah). The importances are listed under what I assume is an attribute of the S4 object that has the same name as the method of calculation used. So, if I used the "lmg" method, I can get the variable importances calculated using that method with rel.imp$lmg.

The problem I am encountering is when I try to use a for loop to calculate the importances using each method to compare the results. See below:

library(relaimpo)
types <- c("lmg", "last", "first", "betasq", "pratt", "genizi", "car")

for (tp in types) {
  rel.imp <- calc.relimp(model, type = tp, rela = T)
  print(rel.imp$tp)
}

This loop returns the following error during the first iteration: Error in h(simpleError(msg, call)) : error in evaluating the argument 'x' in selecting a method for function 'print': no slot of name "tp" for this object of class "relimplm"

When referenced relative to the relimplm object, what should be a different string each time, i.e. "lmg", "last", and so on, is evaluated literally as "tp", the abstract name for each string in the vector I'm trying to iterate over.

If I were using a dataframe and this hadn't worked, I would just try using select() from dplyr. But the object cannot be coerced into a dataframe, so I have to find another data type to convert it to or learn how to work with S4 objects in a for loop. All I want is a list of the relative importances using each method. What is the best way forward to achieve that result?

  • You can't use the `$` operator that way, but you can use the `[[` operator. Have you tried `print(rel.imp[[tp]])` in your loop? – Allan Cameron Aug 15 '20 at 20:29
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. If `[[` doesn't work, then `slot()` might. It kind of depends on how the object was written that's why a reproducible example is always helpful. – MrFlick Aug 15 '20 at 20:52

0 Answers0