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.
<
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