Search code examples
rmachine-learningdecision-treerweka

Output J48 Tree in Text File in R


I have got the decision tree for churn data set using J48()function from RWeka package. 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.


Solution

  • 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