对于下面的代码,我希望找到xerror最低的最小cp项
data(iris)
install.packages("rpart")
library(rpart)
set.seed(161)
tree.model1<-rpart(Sepal.Length~., data = iris)
install.packages("rpart.plot")
library(rpart.plot)
rpart.plot(tree.model1)
tree.model2<-rpart(Sepal.Length~., data = iris, cp=0.005)
tree.model2$cptable
par(mfrow=c(1,2))
rpart.plot(tree.model1)
rpart.plot(tree.model2)
which.min(tree.model2$cptable[,"xerror"])
我的问题集中在最后一行,如果我把
which.min(tree.model2$cptable[, xerror]
不行
这里加引号的作用是什么?
答案 0 :(得分:1)
R 语法规定在使用字符串索引时使用引号。我认为您的困惑是,由于 xerror
是一个变量名,您通常使用它而不在其他行中引用它,因此您希望它是相同的。但是,您必须看到变量的索引和变量本身之间的区别。
因此,使用 []
(索引)不允许您在不带引号的情况下使用 xerror
,但是当您使用 which.min(tree.model2$cptable[,4])
时它会起作用,例如,因为 xerror
是 "xerror"
中的第 4 列(cptable
的另一个索引)。
随着您进一步使用 R,您将开始掌握这些内容。另一个技巧是巧妙地编写和注释您的代码,以便您和其他人都能轻松理解。