## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>",
                      fig.width = 8, fig.height = 5, out.width = "100%")
library(transitiontrees)

## ----fit----------------------------------------------------------------------
data(trajectories)
dim(trajectories)

tree <- context_tree(trajectories, max_depth = 3L, min_count = 5L)
tree

## ----long---------------------------------------------------------------------
data(group_regulation_long)
head(group_regulation_long)
tree_long <- context_tree(group_regulation_long,
                          actor = "Actor", time = "Time", action = "Action",
                          max_depth = 2L, min_count = 5L)
n_nodes(tree_long)

## ----inspect------------------------------------------------------------------
summary(tree)
model_fit(tree)   # logLik, df, nobs, AIC, BIC, perplexity

## ----tables-------------------------------------------------------------------
common_pathways(tree, top = 6)      # by frequency
divergent_pathways(tree, top = 6)   # by divergence from the shorter history
sharp_pathways(tree, top = 6)       # by how peaked the next-state prediction is

## ----prune--------------------------------------------------------------------
pruned <- prune_tree(tree, criterion = "G2", alpha = 0.05)
pruned

## ----predict------------------------------------------------------------------
predict(pruned, c("Active", "Active"), type = "class")          # most likely next
round(predict(pruned, c("Active", "Active"), type = "prob"), 3) # full distribution

## ----plot, fig.width = 14, fig.height = 8-------------------------------------
plot(pruned)

## ----traj-fit-----------------------------------------------------------------
data(ai_long)
tree_ai   <- context_tree(ai_long, actor = "project", session = "session_id",
                         action = "code", max_depth = 3L, min_count = 10L)
pruned_ai <- prune_tree(tree_ai)
tree_ai

## ----traj-frequency, fig.width = 11, fig.height = 7---------------------------
plot_trajectories(tree_ai, measure = "frequency", min_count = 20L)

## ----traj-predictability, fig.width = 11, fig.height = 7----------------------
plot_trajectories(pruned_ai, measure = "predictability", min_count = 20L)

