## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7.2,
  fig.height = 5,
  out.width = "100%"
)
has_partykit <- requireNamespace("partykit", quietly = TRUE)

## ----quickstart---------------------------------------------------------------
library(chaidr)

data(penguins)
fit <- chaid(species ~ ., data = penguins,
             control = chaid_control(min_parent = 30, min_child = 10))
print(fit)

## ----plot, fig.height=6-------------------------------------------------------
plot(fit, main = "CHAID: penguins (species)")

## ----predict------------------------------------------------------------------
pred <- predict(fit, penguins)          # class labels (factor)
mean(pred == penguins$species)          # training accuracy

round(predict(fit, head(penguins, 3), type = "prob"), 3)  # probabilities
predict(fit, head(penguins, 3), type = "node")            # terminal node ids

## ----titanic------------------------------------------------------------------
tit <- as.data.frame(Titanic)
fit_std <- chaid(Survived ~ Class + Sex + Age, data = tit, freq = tit$Freq)
fit_ex  <- chaid(Survived ~ Class + Sex + Age, data = tit, freq = tit$Freq,
                 method = "exhaustive")
print(fit_ex)

## ----reporting----------------------------------------------------------------
tb <- chaid_table(fit, target = "Gentoo")
tb[, setdiff(names(tb), "rule")]

head(chaid_rules(fit, format = "sql"), 3)

chaid_importance(fit)

## ----gains, fig.height=4.5----------------------------------------------------
g <- chaid_gains(fit_std, target = "Yes")
print(g)
plot(g)

## ----validate-----------------------------------------------------------------
set.seed(9)
idx <- sample(nrow(penguins), 244)
fit_tr <- chaid(species ~ ., data = penguins[idx, ],
                control = chaid_control(min_parent = 30, min_child = 10))
chaid_validate(fit_tr, penguins[-idx, ])

## ----viz, eval = FALSE--------------------------------------------------------
# chaid_graphviz(fit)              # 'Graphviz' via DiagrammeR (publication quality)
# chaid_dot(fit, file = "tree.gv") # raw DOT export for the dot CLI
# chaid_plotly(fit)                # interactive htmlwidget with hover details

## ----partykit, eval = has_partykit, fig.height=6------------------------------
pt <- chaid_as_party(fit, penguins)   # pass the data used for fitting
plot(pt)

