1

我正在使用函数 varImp()。

我拟合了一棵树,然后使用 varImp() 查看哪些变量最重要。我想从 varImp() 的输出中提取最重要的变量名。但是输出似乎是一个列表,无法获取变量名称,只有变量重要性的数字权重。

我尝试将输出转换为数据框并使用 names() ,但都不允许我获取重要的变量名称。

这是一个例子:

> # Sample data
> head(Orthodont)
Grouped Data: distance ~ age | Subject
  distance age Subject  Sex
1     26.0   8     M01 Male
2     25.0  10     M01 Male
3     29.0  12     M01 Male
4     31.0  14     M01 Male
5     21.5   8     M02 Male
6     22.5  10     M02 Male
> sample_tree <- rpart(distance ~ ., data = Orthodont)
> varImp(sample_tree)
          Overall
age     1.1178243
Sex     0.5457834
Subject 2.8446154
> names(varImp(sample_tree))
[1] "Overall"
> as.data.frame(varImp(sample_tree))
          Overall
age     1.1178243
Sex     0.5457834
Subject 2.8446154
> # What I want are the names of the two most important variables.
4

1 回答 1

2

您要查找的名称在对象的 rownames() 中。

imp <- varImp(sample_tree)
rownames(imp)[order(imp$Overall, decreasing=TRUE)]

输出:

[1] "Sex"     "age"     "Subject"

因此,根据这些分数,两个最重要的变量是:

rownames(imp)[order(imp$Overall, decreasing=TRUE)[1:2]]

这使:

[1] "Sex"     "age"
于 2014-08-07T19:13:37.130 回答