How to turn ctree nodes into a vector?

159 Views Asked by At

I'll explain my problem using an example with the iris table. Let's say I want to create a tree between sepal width and species. For this I will use this code:

ctree(Species~Sepal.Width,data=iris)->a
plot(a,type="simple")

The problem is that, if I want to do a data frame, for example counting the quantity of cases in each node (from 0 to 2.9; 2.9 to 3.3, etc), the only way I've found to do this is by creating a new vector manually and then using the dcast or table function.

The problem with this solution is that if I had a bigger tree result, it could be quite difficult. Do you know any other solution for this? Thanks a lot.

1

There are 1 best solutions below

3
On

Actually, the party structure created by ctree has that information stored in it. Using your example, a[1]$fitted[,1] has which leaf each point ended up in. So you can get the number of points at each leaf with:

table(a[1]$fitted[,1])
 3  4  5 
57 56 37 

If you are trying to see the rules that go with the leaf numbers, you can use:

partykit:::.list.rules.party(a)
                                        3 
"Sepal.Width <= 3.3 & Sepal.Width <= 2.9" 
                                        4 
 "Sepal.Width <= 3.3 & Sepal.Width > 2.9" 
                                        5 
                      "Sepal.Width > 3.3"