陳寧寬
陳寧寬

Reputation: 63

compute numbers of leaf in rpart

i use rpart run a regression tree

library(MASS)
N = 1000
episolon = rnorm(N, 0, 0.01)
x1 = rnorm(N, 0, sd=1)
x2 = rnorm(N, 0, sd=1)
eta_x = 1/2*x1+x2
Kappa_x = 1/2*x1
w = rbinom(N, 1, 0.5)
treatment = w
makeY = function(eta, Kappa){
  Y = eta+1/2*(2*w-1)*Kappa+episolon
}
Y1 = makeY(eta_x, Kappa_x)
fit = rpart(Y1 ~ x1 + x2)
plot(fit)
text(fit)

compute numbers of leaf in rpart

I want to have a function to give me there are 12 leaves in this tree

Upvotes: 1

Views: 2010

Answers (1)

G5W
G5W

Reputation: 37661

The fit object has all the information that you need. You can examine it using str(fit).

Two ways to find the number of leaves are:

sum(fit$frame$ncompete == 0)
[1] 11

AND

sum(fit$frame$var == "<leaf>")
[1] 11

Upvotes: 3

Related Questions