实现varImp以实现变量的重要性和绘图

时间:2019-07-27 15:37:25

标签: r r-caret

enter image description here我正在尝试为以下模型绘制变量重要性得分。

得分输出正常,但是绘制不正确-我需要在代码中添加另一个参数吗?

分数的代码和输出如下。

library(caret)
#GENERALISED LINEAR MODEL
LR_swim <- lm(racetime_mins ~ event_date+ event_month +year +event_id + 
            gender + distance_new + New_Condition+
            raceNo_Updated +  
            handicap_mins +points+
              Wind_Speed_knots+ 
             Air_Temp_Celsius +Water_Temp_Celsius +Wave_Height_m,
               data = SwimmingTrain) 
           family=gaussian(link = "identity")

varImp2<-varImp(object=LR_swim)
plot(varImp2,main="Variable Importance")

总体 event_date 24.463358 event_month 22.358448 年24.399390 event_id 26.878342 性别女性30.422470 性别男13.273062 distance_new 248.727351 新条件22.574999 raceNo_Updated 9.812053 残障人士分钟134.914137 点40.443116 风速结14.492203 Air_Temp_Celsius 16.562194 Water_Temp_Celsius 2.861662 Wave_Height_m 8.592716

#ClassOutput
class(varImp2)
[1] "data.frame"
#HeadOutput
> head(varImp2)
          Overall
event_date   24.46336
event_month  22.35845
year         24.39939
event_id     26.87834
genderfemale 30.42247
gendermale   13.27306

我的样子;

应该看起来像

enter image description here

2 个答案:

答案 0 :(得分:0)

根据所需的结果,您的目标是从数据框中绘制数字列,并按该列中的值在y轴上对其进行排序。我将以mtcars数据集为例。

library(caret)
LR_mtcars <- glm(mpg ~ ., data = mtcars, family = gaussian)
varImp2 <- varImp(LR_mtcars)

varImp2是一个数据框。现在添加一个名为“标签”的列。我们将此列设为factor,然后根据“总体”中的值对其进行排序。

varImp2$labels <- factor(rownames(varImp2))
varImp2$labels <- reorder(varImp2$labels, varImp2$Overall)

然后我们可以绘制值。对于图的第一次迭代,我们将x和y轴的标题留为空白,并将y轴的标签留为空白。然后,我们将它们添加回去。

plot(x = varImp2$Overall, y = varImp2$labels, main = "Variable Importance", 
  yaxt = "n", ylab = "", xlab = "")
axis(2, at = 1:nrow(varImp2), labels = levels(varImp2$labels), las = 2)
title(xlab = "Importance")

这给了我们

enter image description here

答案 1 :(得分:0)

好吧,在命令中我问过std::vector的行名是否是绘图中所需的x值,但您没有告诉。无论如何,假设行名是您要分配的y值,那么这些代码将为您提供所需的绘图,您可以自己排列x和y。

varImp2

enter image description here