带引号和不带引号有什么区别
with quotation mark and without quotation mark, what is the difference
对于以下代码,我希望找到具有最低 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]
没用
这里加引号有什么作用?
R 语法规定在使用字符串进行索引时使用引号。我认为您的困惑是,由于 xerror
是一个变量名,并且您通常在不在其他行中引用的情况下使用它,所以您希望它是相同的。但是,您必须看到变量的索引和变量本身之间的区别。
因此,[]
(索引)的使用不允许您在没有引号的情况下使用 xerror
,但是当您使用 which.min(tree.model2$cptable[,4])
时它会起作用,例如,因为 xerror
是 cptable
.
中的第 4 列("xerror"
的另一个索引)
随着您进一步使用 R,您将开始掌握这些内容。另一个技巧是整洁地编写和注释您的代码,以便您和其他人都能轻松理解。
对于以下代码,我希望找到具有最低 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]
没用
这里加引号有什么作用?
R 语法规定在使用字符串进行索引时使用引号。我认为您的困惑是,由于 xerror
是一个变量名,并且您通常在不在其他行中引用的情况下使用它,所以您希望它是相同的。但是,您必须看到变量的索引和变量本身之间的区别。
因此,[]
(索引)的使用不允许您在没有引号的情况下使用 xerror
,但是当您使用 which.min(tree.model2$cptable[,4])
时它会起作用,例如,因为 xerror
是 cptable
.
"xerror"
的另一个索引)
随着您进一步使用 R,您将开始掌握这些内容。另一个技巧是整洁地编写和注释您的代码,以便您和其他人都能轻松理解。