'rpart() inside a function doesn't show variable names

I have the following problem: The goal is to put rpart () in a function so the set-up can be quickly done for different variables and datasets. Whenever rpart() is written in a function it seems to have some problems with different environments. Both for finding the assigned variables as in the names of the variables in the tree.

For instance if you look to the example below, the name 'parameter' is used at each splitting node.

I tried already solving the problem with get() (which gives the error 'Error in get(parameter) : invalid first argument'. I also tried environment(research.parameter)<-environment() which makes the function work, but still isn't showing the assigned variable names in the splitting in the tree.

[Result function tree][1]

Example code:

  attach(Data.used)
  environment(research.parameter)<-environment()
  environment(parameter)<-environment()
  fit <- rpart(research.parameter ~ parameter,data=Data.used)
  printcp(fit)

  rpart.plot(fit, type=0, tweak=1.5,main= title.tree) 


  File <- paste("Decisiontree_",research.parameter,"_",title.tree,"_",date,".png",sep = "")     #png voor cross-validation results
       png(File, units = "in", width = 15, height = 10, res=300) 
       
  rpart.plot(fit, type=5, tweak=1.5, main= title.tree,cex.main=3) 

  dev.off()
}

Plot.tree.2(Data.used = train.data, parameter=IT+RE,research.parameter = Mmean, title.tree = "test")```


  [1]: https://i.stack.imgur.com/8avE3.png


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source