I am new to R and I am trying out a Classification decision tree using party:ctree library. All seems to be fine. I get the expected result and a well describing plot.
Now if i want to extract the results from the summary of the fit, I ahve to traverse to each node and extract information. Fortunately this is already written by @baydoganm here. I want to extend this code and write the results to a dataframe instead of printing it.
reproducible code :
library(party)
ct <- ctree(Species ~ ., data = iris)
traverse <- function(treenode){
if(treenode$terminal){
bas=paste(treenode$nodeID,treenode$prediction)
print(bas) #here the results are printed
return(0)
}
traverse(treenode$left)
traverse(treenode$right)
}
traverse(ct@tree) #function call
This works fine and i get the output on console. Now if i want to write the results to a data frame, I am facing problems.
What i tried so far: tried to write to a list using mutable closures(). But not sure how to get it working.
l <- list()
count = 0
traverse1 <- function(treenode,l){
if((treenode$terminal == T)){
count <<- count + 1
print(count)
node = c(treenode$nodeID)
pred = c(treenode$prediction)
l[[count]] <- data.frame(node,pred) #write results in the dataframe
}
traverse1(treenode$left,l)
traverse1(treenode$right,l)
}
test <- traverse1(ct@tree,l)# function call
I get only the results of my last call to the function and rest are null