## Function to either
# A: convert pretty.gbm.tree data frames into the same format as for 'tree'
# https://stats.stackexchange.com/questions/41443/how-to-actually-plot-a-sample-tree-from-randomforestgettree
# or B: plot pretty.gbm.tree outputs directly using dendrogram plots:
# http://gastonsanchez.com/blog/how-to/2012/10/03/Dendrograms.html
#### Generate or load a gbm object####
setwd("C:/Users/Simon Dedman/Dropbox/Galway/Analysis/R/P1 Map analysis")
load("Bin_Best_Model")
# show first tree matrix:
pretty.gbm.tree(Bin_Best_Model,1)
# create an object from it
tree1.df <- pretty.gbm.tree(Bin_Best_Model,1)
# list gbm variables (list position corresponds to SplitVar+1 (splitvar=0 is the first variable))
Bin_Best_Model$var.names
####Convert to randomForest getTree format####
# create blank df w/ [L,W] = max(tree1.df$row.names)+1,8]
# col names: "row.names", "left daughter", "right daughter", "split var", "split point", "status", "prediction", "weight"
tree2.df <- data.frame("row.names"=1:length(tree1.df$SplitVar),
"left daughter"=tree1.df$LeftNode,
"right daughter" = tree1.df$RightNode,
"split var" = tree1.df$SplitVar,
"split point" = tree1.df$SplitCodePred,
status = rep(1,length(tree1.df$SplitVar)),
prediction = tree1.df$Prediction,
weight = tree1.df$Weight)
# in splitvar replace -1 with NA
tree2.df$split.var<-replace(tree2.df$split.var,tree2.df$split.var==-1,NA)
# in splitvar, replace values with variable names
tree2.df$split.var<-Bin_Best_Model$var.names[tree2.df$split.var+1]
# status: if split.var is NA then change to -1 else leave as 1
tree2.df$status<-replace(tree2.df$status,is.na(tree2.df$split.var),-1)
## add 1 to left & right daughter values
tree2.df$left.daughter<-tree2.df$left.daughter+1
tree2.df$right.daughter<-tree2.df$right.daughter+1
# In prediction, changes values to NA if row isn't a terminal node (status = 1)
tree2.df$prediction<-replace(tree2.df$prediction,tree2.df$status==1,NA)
#Is this even useful? On the web page they then wonder how to convert THIS to one generated by 'tree'
# Elith made hers in MS Paint so don't bother!
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.