musik lover
musik lover

Reputation: 29

How to sort a different column from varImp function in R

I'm using the varImp(model, scale = FALSE) function for multiclass and got a result of 20 most important variables with three columns since there are three classes. It is currently sorted based on the first column, but is there any way to sort it based on the second column? I tried sorting it and convert to dataframe, it doesn't work: cannot coerce class ‘"varImp.train"’ to a data.frame.

Upvotes: 0

Views: 541

Answers (1)

StupidWolf
StupidWolf

Reputation: 46898

My guess is that you are using randomForest with caret, otherwise the varImp() function will not work.

please provide this information in your question.

So you can store the varImp() results and sort after:

library(caret)
rf = train(Species ~ .,data=iris,method="rf",trControl=trainControl(method="cv"),importance=TRUE)

varImp(rf,scale=FALSE)
rf variable importance

  variables are sorted by maximum importance across the classes
             setosa versicolor virginica
Petal.Length 22.013    33.4341    27.738
Petal.Width  22.454    32.3445    30.897
Sepal.Length  6.649     8.6931     8.569
Sepal.Width   4.420    -0.8063     3.560

res = varImp(rf,scale=FALSE)$importance

Sort by second column,

res[order(res$versicolor,decreasing=TRUE),]

                setosa versicolor virginica
Petal.Length 22.013431  33.434069 27.738319
Petal.Width  22.453571  32.344497 30.897214
Sepal.Length  6.649072   8.693132  8.569421
Sepal.Width   4.419712  -0.806256  3.559570

Upvotes: 1

Related Questions