Testing rules generated by Rpart package

后端 未结 2 706
不知归路
不知归路 2021-02-09 08:42

I want to test in a programmatically way one rule generated from a tree. In the trees the path between the root and a leaf (terminal node) could be interpreted as a rule.

<
2条回答
  •  臣服心动
    2021-02-09 09:22

    In general I don't recommend using eval(parse(...)) but in this case it seems to work:

    Extract the rule:

    rule <- unname(unlist(path.rpart(model, nodes=7)))[-1]
    
     node number: 7 
       root
       Petal.Length>=2.45
       Petal.Width>=1.75
    rule
    [1] "Petal.Length>=2.45" "Petal.Width>=1.75" 
    

    Extract the data using the rule:

    node_data <- with(iris, iris[eval(parse(text=paste(rule, collapse=" & "))), ])
    head(node_data)
    
        Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
    71           5.9         3.2          4.8         1.8 versicolor
    101          6.3         3.3          6.0         2.5  virginica
    102          5.8         2.7          5.1         1.9  virginica
    103          7.1         3.0          5.9         2.1  virginica
    104          6.3         2.9          5.6         1.8  virginica
    105          6.5         3.0          5.8         2.2  virginica
    

提交回复
热议问题