Joe Joe - 4 months ago 28
R Question

Output J48 Tree in Text File in R

I have got the decision tree for churn using J48 function. The tree is really big hence I am unable to see the whole tree. I want to output it in a text file but the format is getting changed. How can I save it preserving the tree format.

save(m2,file="thisexample.txt", ascii=TRUE)

m2 is the dataframe in which I am storing the J48 tree output.

Answer

I. Example with iris data set using RWeka's J48() function.

      library(RWeka)
      result = J48(Species~.,data=iris)
      result
      # J48 pruned tree
      # ------------------

      # Petal.Width <= 0.6: setosa (50.0)
      # Petal.Width > 0.6
      # |   Petal.Width <= 1.7
      # |   |   Petal.Length <= 4.9: versicolor (48.0/1.0)
      # |   |   Petal.Length > 4.9
      # |   |   |   Petal.Width <= 1.5: virginica (3.0)
      # |   |   |   Petal.Width > 1.5: versicolor (3.0/1.0)
      # |   Petal.Width > 1.7: virginica (46.0/1.0)

      # Number of Leaves  :     5

      # Size of the tree :      9

II. Use sink() function to write it in a text file

      sink("result.txt")
      print (result)
      sink()

III. Open result.txt saved in your current working directory.

enter image description here