为什么cv.tree()在从函数内部调用时找不到这个对象?

时间:2015-07-16 19:55:49

标签: r scope

在函数中调用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提示符调用每一行时,相同的功能代码有效。

1 个答案:

答案 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)
}

在此处找到答案:http://florence.acadiau.ca/collab/hugh_public/index.php?title=R:putting_cv.tree_inside_a_function&redirect=no