I seem to have a namespace or scope issue when calling 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
The cv.tree() call to model.frame(object) fails. The same function code works when I call each line from the R prompt.
Not sure why this happens but it can be fixed by creating a tree with the argument model = T. Using the example above:
mytreecv = function(formula, mydata)
{
set.seed(2)
tree.carseats = tree(formula, mydata, model = T)
cv.carseats = cv.tree(tree.carseats, FUN=prune.misclass)
}
Answer found here: http://florence.acadiau.ca/collab/hugh_public/index.php?title=R:putting_cv.tree_inside_a_function&redirect=no
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With