Repository navigation
Expand file tree
/
Copy pathdrawTrees.R
More file actions
80 lines (69 loc) · 2.48 KB
/
Copy pathdrawTrees.R
File metadata and controls
80 lines (69 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# Usage:
# > source('drawTrees.R')
#
# Draws trees from random forest model
#
# To use this function:
# (1) place this file in your working directory
# (2) use the source function in your script to import this code
# ex) source("drawTrees.R")
# (3) call the function
# ex) drawTrees(randomForestModel)
#
# Uses the reprtree package by araastat
# https://github.com/araastat/reprtree
# Checks if required packages are installed and installs missing packages
#
# If installing reprtree fails, it may be because OpenSSL is not installed
# 'devtools' requires the git2r package which is only installed using OpenSSL
# See error messages in console for more information
#
# INPUT:
# model : randomForest model from package 'randomForest'
# random forest models from other packages may not work
# filename : name of pdf file containing tree diagrams
# default = "TreeDiagrams.pdf"
# OUTPUT:
# PDF file containing tree diagrams
#args <- commandArgs( trailingOnly = TRUE )
#if( length( args ) < 2 )
# {
# cat( "Usage: Rscript drawTrees.R inputModel outputFile ", sep = "" )
# stopQuietly()
# }
#inputModel <- args[1]
#outputFile <- args[2]
drawTrees <- function(model, filename="TreeDiagrams.pdf") {
# Check if reprtree packages installed. If not, install reprtree
# and its dependencies
if(!('reprtree' %in% rownames(installed.packages()))) {
print("Installing reprtree package...")
# Check if dependencies are installed. If not, install them
options(repos="http://cran.rstudio.org")
have.packages <- installed.packages()
cran.packages <- c('devtools','plotrix','randomForest','tree')
to.install <- setdiff(cran.packages, have.packages[,1])
if(length(to.install)>0) install.packages(to.install)
# Install reprtree
library(devtools)
install_github('araastat/reprtree')
# Check if installation worked. If not, exit function
if('reprtree' %in% rownames(installed.packages())) {
print("Reprtree installed")
} else {
stop("Installation failed! Try manually installing reprtree package\n")
}
}
library(reprtree, quietly=T)
cat("\nDrawing tree diagrams...\n")
# Set filename, width, and height of output file
pdf(file=filename, width=11, height=8.5)
# For each tree in model, draw tree diagram and print to pdf file
for(i in 1:model$ntree) reprtree:::plot.getTree(model,k=i)
cat("Printed diagrams for", model$ntree, "tree(s) to \"",
filename, "\"\n")
}
#load( inputModel )
#cat("loaded ", inputModel, "\n")
#print(str(modelForest))
#drawTrees( modelForest , outputFile )