【问题标题】:with quotation mark and without quotation mark, what is the difference带引号和不带引号有什么区别
【发布时间】:2021-09-18 17:22:59
【问题描述】:

对于以下代码,我希望找到具有最低 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] 不行

这里加引号有什么作用?

【问题讨论】:

  • 加上引号,您正在查看名称为"xerror" 的列。如果没有引号,您将查看名称由名称为xerror 的变量的值给出的列。由于xerror 不存在,因此您会收到错误消息。
  • 感谢@Limey 非常有帮助

标签: r decision-tree rpart


【解决方案1】:

R 语法规定在使用字符串进行索引时使用引号。我假设您的困惑是,由于xerror 是一个变量名,并且您通常使用它而不在其他行中引用,因此您希望它是相同的。但是,您必须看到变量索引和变量本身之间的差异。

因此,[](索引)的使用不允许您在没有引号的情况下使用xerror,但是当您使用which.min(tree.model2$cptable[,4]) 时它会起作用,因为xerror 是第四列(另一个索引"xerror") 在cptable

随着您使用 R 的进一步发展,您将开始学习这些内容。另一个提示是整齐地编写和注释您的代码,以便您和其他人都能轻松理解。

【讨论】:

    猜你喜欢
    • 2011-05-19
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    • 2014-05-13
    • 2015-08-16
    • 2017-05-14
    • 2010-12-31
    相关资源
    最近更新 更多