Search code examples
rdata-miningdecision-treerpart

How can I get the data in one terminal node of a decision tree in RPART


Suppose I have a decision tree from rpart, How can I get all the data points in one node without writing all the conditions?

For example, How can I get 17 data points in Node 3, without writing if else on all splits?

library(rpart)
library(partykit)
fit=rpart(factor(am)~.,mtcars,control=rpart.control(minsplit = 2),cp=0)
plot(as.party(fit))

enter image description here


Solution

  • Try this:

    fit$where[fit$where==3] # for Node 3
    #  Hornet 4 Drive   Hornet Sportabout             Valiant          Duster 360           Merc 240D            Merc 280           Merc 280C 
    #              3                   3                   3                   3                   3                   3                   3 
    #     Merc 450SE          Merc 450SL         Merc 450SLC  Cadillac Fleetwood Lincoln Continental   Chrysler Imperial    Dodge Challenger 
    #              3                   3                   3                   3                   3                   3                   3 
    #    AMC Javelin          Camaro Z28    Pontiac Firebird 
                  3                   3                   3 
    length(fit$where[fit$where==3])
    #[1] 17
    
    mtcars[rownames(mtcars) %in% names(fit$where[fit$where==3]),]
    #                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb  x
    #Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1  4
    #Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2  5
    #Valiant             18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1  6
    #Duster 360          14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4  7
    #Merc 240D           24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2  8
    #Merc 280            19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4 10
    #Merc 280C           17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4 11
    #Merc 450SE          16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3 12
    #Merc 450SL          17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3 13
    #Merc 450SLC         15.2   8 275.8 180 3.07 3.780 18.00  0  0    3    3 14
    #Cadillac Fleetwood  10.4   8 472.0 205 2.93 5.250 17.98  0  0    3    4 15
    #Lincoln Continental 10.4   8 460.0 215 3.00 5.424 17.82  0  0    3    4 16
    #Chrysler Imperial   14.7   8 440.0 230 3.23 5.345 17.42  0  0    3    4 17
    #Dodge Challenger    15.5   8 318.0 150 2.76 3.520 16.87  0  0    3    2 22
    #AMC Javelin         15.2   8 304.0 150 3.15 3.435 17.30  0  0    3    2 23
    #Camaro Z28          13.3   8 350.0 245 3.73 3.840 15.41  0  0    3    4 24
    #Pontiac Firebird    19.2   8 400.0 175 3.08 3.845 17.05  0  0    3    2 25