Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cv.tree() can't find this object when called from inside a function?

Tags:

scope

r

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.

like image 900
Robert Kubrick Avatar asked Oct 18 '25 07:10

Robert Kubrick


1 Answers

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

like image 94
admccurdy Avatar answered Oct 19 '25 21:10

admccurdy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!