Why can't cv.tree () find this object when called from within a function?
I seem to have a namespace or scope when I call cv.tree () inside a function:
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)
}
When I run mytreecv () I get this error:
> mytreecv(High ~ . - Sales, Carseats)
Error in is.data.frame(data) (from #5) : object 'mydata' not found
A call to cv.tree () is made on the model.frame (object). The same function code works when I call each line from the R prompt.
+3
source to share
1 answer
Not sure why this is happening, but it can be fixed by creating a tree with model = T argument. Using the above example:
mytreecv = function(formula, mydata)
{
set.seed(2)
tree.carseats = tree(formula, mydata, model = T)
cv.carseats = cv.tree(tree.carseats, FUN=prune.misclass)
}
The answer is found here: http://florence.acadiau.ca/collab/hugh_public/index.php?title=R:putting_cv.tree_inside_a_function&redirect=no
0
source to share