0

I'd like to create a function to display the result of rpart with partykit. I converted the result of rpart with as.party with the following code and displayed the tree structure.

library(partykit)
library(rpart)

result1 <- rpart(Species~.,data = iris)
plot(as.party(result1))

So, I defined rpart and as.party in the function and executed it.

rpart_party <- function(formula, data){
  result1 <- rpart(formula = formula ,data = data)
  return(as.party(result1))
}
plot(rpart_party(Species~., data = iris))

However, the following error occurred.

Error in eval(predvars, data, env) : 
  invalid 'envir' argument of type 'closure'

Please tell me how to create a function that transforms the result of rpart with as.party and displays the structure of the tree.

Achim Zeileis
  • 15,710
  • 1
  • 39
  • 49

1 Answers1

2

You need to wrap your evaluation of the formula in something like substitute(...) to prevent the model call being set to "formula" instead of "Species~." etc.

rpart_party <- function(formula, data){
  result1 <- rpart(formula = substitute(formula), data = data)
  return(as.party(result1))
}
Esther
  • 1,115
  • 1
  • 10
  • 15
  • Alternatively, `rpart(formula = formula, data = data, model = TRUE)` can be used. This stores the `model.frame` in `result1` so that `as.party()` does not have to re-evaluate this and try to look in the right environment... – Achim Zeileis Aug 20 '18 at 22:49