在函数中调用cv.tree()时,我似乎有一个名称空间或作用域问题:
library(tree)
library(ISLR)
Carseats$High = ifelse(Sales <= 8, "No", "Yes")
mytreecv = function(formula, mydata)
{
set.seed(2)
tree.carseats = tree(formula, mydata)
cv.carseats = cv.tree(tree.carseats, FUN=prune.misclass)
}
当我运行mytreecv()时出现此错误:
> mytreecv(High ~ . - Sales, Carseats)
Error in is.data.frame(data) (from #5) : object 'mydata' not found
对model.frame(object)的cv.tree()调用失败。当我从R提示符调用每一行时,相同的功能代码有效。
答案 0 :(得分:0)
不确定为什么会发生这种情况,但可以通过创建参数model = T的树来修复。使用上面的示例:
mytreecv = function(formula, mydata)
{
set.seed(2)
tree.carseats = tree(formula, mydata, model = T)
cv.carseats = cv.tree(tree.carseats, FUN=prune.misclass)
}