对象“i”在 R for 循环中未找到(k 折交叉验证)
就像标题所说的那样,我正在尝试进行K-折叠的交叉验证。我的编码技巧非常基本,请尽可能简单地解释。
library(ISLR)
install.packages("ISLR")
library(ISLR)
install.packages("boot")
library(boot)
data <- attach(read.csv("TutWk7Data-1.csv",header=TRUE))
MSE = NULL
for (i in 1:7){
model = glm(Y~poly(X,i),data=data)
MSE[i] = cv.glm(data,model,K=10)$delta[1]
}
我有这个错误
Error in poly(X,i):object "i" not found
Like the title says, I am trying to do k-fold cross validation. My coding skills are very basic, please explain as simply as possible.
library(ISLR)
install.packages("ISLR")
library(ISLR)
install.packages("boot")
library(boot)
data <- attach(read.csv("TutWk7Data-1.csv",header=TRUE))
MSE = NULL
for (i in 1:7){
model = glm(Y~poly(X,i),data=data)
MSE[i] = cv.glm(data,model,K=10)$delta[1]
}
I get this error
Error in poly(X,i):object "i" not found
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是由于您使用
attach
引起的。根据attach
的帮助页面,您将该环境存储在
data
对象中。另一方面,cv.glm
的帮助页面指出“data”参数必须是“包含数据的矩阵或数据框”。您可以在运行时检查这一点:因为
data
不是数据帧(即使它的行为非常像数据帧!),所以当您将其传递给cv 时,所有的赌注都将消失.glm
.正如评论者所说,删除
attach
调用:它是多余的(并且无论如何都有看不见的副作用)。这是您可能想要的一个工作示例:The problem arises from your use of
attach
. According to the help page forattach
,You stored that environment in the
data
object. On the other hand, the help page forcv.glm
states the "data" argument must be a "matrix or data frame containing the data." You can check this at run time:Because
data
is not a data frame (even though it can behave remarkably like one!), all bets are off when you pass it tocv.glm
.As remarked by a commenter, delete the
attach
call: it's superfluous (and has invisible side-effects anyway). Here is a working example of what you likely intended: