| Title: | Dynamic, Probabilistic, and Higher-Order Network Analysis |
| Version: | 1.2.0 |
| Description: | Estimates, compares and tests networks from sequence, event-log, panel and cross-sectional data through one interface, build_network(). Sequence data give transition, frequency, co-occurrence, attention-weighted, n-gram, gap and reply networks, following transition network analysis Saqr et al. (2025) <doi:10.1145/3706468.3706513>, and reply networks weighted by response latency Templeton et al. (2022) <doi:10.1073/pnas.2116915119>. Psychological networks are estimated by correlation, partial correlation, graphical lasso, Ising and mixed graphical models Saqr, Beck, and Lopez-Pernas (2024) <doi:10.1007/978-3-031-54464-4_19>, together with multilevel vector autoregression Epskamp et al. (2018) <doi:10.1080/00273171.2018.1454823> and the network comparison test van Borkulo et al. (2022) <doi:10.1037/met0000476>. Higher-order methods cover higher-order networks, hyper-path anomalies, multi-order generative models, hypergraphs and simplicial complexes. Inference includes bootstrap, permutation and Bayesian comparison, split-half reliability and centrality stability. Further tools fit mixtures of Markov chains and cluster sequences, test Markov order, and compute transition entropy, passage times, stability landscapes, sequence patterns and indices, and association tests for counts nested in actors. |
| License: | MIT + file LICENSE |
| URL: | https://github.com/mohsaqr/Nestimate, https://pak.dynasite.org/Nestimate/ |
| BugReports: | https://github.com/mohsaqr/Nestimate/issues |
| Language: | en-US |
| Encoding: | UTF-8 |
| RoxygenNote: | 7.3.3 |
| Imports: | ggplot2, data.table, cluster, scales, brglm2, nnet, idiographic (≥ 0.3.4), psychnets (≥ 0.5.2) |
| Suggests: | testthat (≥ 3.0.0), igraph, glmnet, lavaan, stringdist, gridExtra, lme4, corpcor, Matrix, cograph (≥ 2.4.4), ggfittext, knitr, rmarkdown, tibble, tna |
| Config/testthat/edition: | 3 |
| Depends: | R (≥ 4.1.0) |
| LazyData: | true |
| VignetteBuilder: | knitr |
| NeedsCompilation: | no |
| Packaged: | 2026-11-25 19:43:24 UTC; saqrserver |
| Author: | Mohammed Saqr [aut, cre, cph], Sonsoles López-Pernas [aut], Kamila Misiejuk [aut] |
| Maintainer: | Mohammed Saqr <saqr@saqr.me> |
| Repository: | CRAN |
| Date/Publication: | 2026-11-26 08:40:28 UTC |
Nestimate: Dynamic, Probabilistic, and Higher-Order Network Analysis
Description
Nestimate estimates networks from sequences, event logs, one-hot codes and
panel data, compares them, and tests how far they can be trusted. One
entry point, build_network(), estimates transition networks
(transition probabilities, frequencies, co-occurrence and
attention-weighted transitions; Saqr et al. 2025, doi:10.1145/3706468.3706513) and
psychological networks (correlation, partial correlation, graphical lasso
and Ising models, Saqr, Beck and López-Pernas 2024,
doi:10.1007/978-3-031-54464-4_19; and mixed graphical models), and
returns a netobject. The other verbs, by the question they answer (most
read a netobject; the panel-data ones read the data directly):
inference on a network:
bootstrap_network(),boot_glasso(), split-half reliability withnetwork_reliability()and centrality stability withcentrality_stability();comparison of networks:
compare_networks(), and the permutation testspermutation()andnct();the structure of a network:
net_centrality(),chain_structure(),passage_time(),markov_stability(),stability_landscape()andtransition_entropy();subgroups: clustering with
build_clusters(), mixed Markov models withbuild_mmm()and multi-cluster multi-layer networks withbuild_mcml();higher-order networks:
build_hon(), higher-order network embedding withbuild_honem(), hyper-path anomalies withbuild_hypa(), the multi-order generative modelbuild_mogen(), andmarkov_order_test();panel data: multilevel vector autoregression with
build_mlvar()and person-specific networks withbuild_gimme().
Author(s)
Maintainer: Mohammed Saqr saqr@saqr.me [copyright holder]
Authors:
Sonsoles López-Pernas sonsoles.lopez@uef.fi
Kamila Misiejuk kamila.misiejuk@fernuni-hagen.de
References
Saqr, M., López-Pernas, S., Törmänen, T., Kaliisa, R., Misiejuk, K., & Tikka, S. (2025). Transition network analysis: A novel framework for modeling, visualizing, and identifying the temporal patterns of learners and learning processes. In Proceedings of the 15th International Learning Analytics and Knowledge Conference (LAK25). ACM. doi:10.1145/3706468.3706513
Saqr, M., Beck, E., & López-Pernas, S. (2024). Psychological networks: A modern approach to analysis of learning and complex learning processes. In M. Saqr & S. López-Pernas (Eds.), Learning Analytics Methods and Tutorials: A Practical Guide Using R. Springer. doi:10.1007/978-3-031-54464-4_19
See Also
Useful links:
Report bugs at https://github.com/mohsaqr/Nestimate/issues
Convert an action column to one-hot columns
Description
action_to_onehot() adds one 0/1 indicator column per state to a data
frame with a categorical action column: the column of a row's state is 1
and the others are 0. The result is the one-hot layout that
build_network() reads with codes or format = "onehot", and wtna()
reads directly.
Usage
action_to_onehot(
data,
action_col = "Action",
states = NULL,
drop_action = TRUE,
sort_states = FALSE,
prefix = ""
)
Arguments
data |
A data frame with an action column. |
action_col |
The action column. Default |
states |
The states to make columns for, in that order. Default
|
drop_action |
Whether to remove the action column. Default |
sort_states |
Whether to sort the state columns alphabetically (in
level order for a factor action column). Default |
prefix |
A prefix for the state column names. Without one, a state
named like an existing column replaces that column. Default |
Value
The input data frame with one integer column per state appended,
named paste0(prefix, state). All other columns are kept; the action
column is removed unless drop_action = FALSE. A row with a missing
action is NA in every state column.
Examples
long_data <- data.frame(
Actor = rep(1:3, each = 4),
Time = rep(1:4, 3),
Action = sample(c("A", "B", "C"), 12, replace = TRUE)
)
onehot_data <- action_to_onehot(long_data)
head(onehot_data)
Tabulate the first and last states of each sequence
Description
actor_endpoints() returns one row per sequence (actor) of a
wide-format sequence table, with its first and last observed states, the
positions where they occur, the number of observed cells and whether the
sequence ends early. A sequence ends early (dropped_out) when its last
observed state comes before the last column, so every cell after it is
missing: the terminal-NA pattern of drop-out, course end or censoring.
Internal gaps do not count.
The flag records only where the observations stop; it cannot say why.
A sequence recorded over fewer positions than the others looks the same
as one that left. mark_terminal_state() turns the terminal-NA cells
into an explicit end state, and chain_structure() then describes the
chain with that state.
Usage
actor_endpoints(data, cols = NULL)
Arguments
data |
The sequences: a matrix or data frame with one row per actor
and one column per position, holding state labels, with |
cols |
The columns holding the positions, in order; the other
columns are ignored. A name not in |
Value
A data frame with one row per actor and the columns:
actorThe row name when
datahas row names other than1,2, ...; otherwise the row number.first_state,last_stateThe first and the last observed state.
first_step,last_stepThe positions (column numbers among the position columns) of the first and the last observed state.
n_observedThe number of observed cells.
dropped_outTRUEwhenlast_stepis before the last column, so the row ends in missing cells.
A row with no observed state has NA states and steps, n_observed
0 and dropped_out FALSE.
See Also
mark_terminal_state(), chain_structure()
Examples
actor_endpoints(trajectories) |> head()
Build a node-level network with clusters as node groups
Description
as_htna() builds the full node-level network from the original data
with build_network() and attaches a cluster to every node, returning a
single htna network: every state is a node, and the clusters group the
nodes. It is the node-level counterpart of build_mcml(): where
build_mcml() collapses the network to a cluster-level (macro) summary,
as_htna() keeps every node and every transition, including the
between-cluster transitions an mcml keeps only in aggregate. It takes
data with a clustering, an mcml (which supplies the clustering, and
often the data), or a fitted net_mmm.
The result is an ordinary netobject, so the inference verbs apply to it
(bootstrap_network(), net_centrality(), permutation()), and cograph::plot_htna() draws it as a grouped network.
Usage
as_htna(x, clusters = NULL, method = "relative", ...)
## S3 method for class 'mcml'
as_htna(x, clusters = NULL, method = "relative", data = NULL, ...)
## S3 method for class 'net_mmm'
as_htna(x, clusters = NULL, method = "relative", ...)
## Default S3 method:
as_htna(x, clusters = NULL, method = "relative", ...)
Arguments
x |
The data, in any form |
clusters |
The cluster of each node: a named list of node-name
vectors, a membership vector with one value per node (in the order of
the built network's nodes, alphabetical for sequence data, or named by
node), or a two-column data frame of node and cluster names. Default |
method |
The estimator passed to |
... |
Further arguments for |
data |
For the |
Details
Why it rebuilds from data
It rebuilds from data because an mcml holds no faithful node-level
network: its macro sequences are recoded to cluster labels, and its
per-cluster data keep only that cluster's states, so the node-level
transitions between clusters survive only in the original data. An
mcml therefore supplies the cluster membership, and either the source
it retained or the data passed supplies the transitions.
Value
For data and mcml input, a single htna network (class
c("htna", "netobject", "cograph_network")) over all nodes. Print it for
an overview, call summary() for its network metrics, and draw it with
cograph::plot_htna(). The clusters are stored as a factor in the
groups column of the node table and as character values in the
group column of node_groups; actor_levels records their order and
is also attached to node_groups, so the partition survives a round
trip. For compatibility, the node table also keeps a cluster column,
and the membership is kept in the "cluster_members" attribute. A
fitted net_mmm returns an htna_group, one HTNA network per sequence
cluster, with the MMM diagnostics kept; a net_mmm fitted on data
without an HTNA actor partition raises an error.
See Also
build_mcml, build_network; plot with
cograph::plot_htna().
Examples
seqs <- data.frame(
t1 = c("A", "C", "E", "B"), t2 = c("B", "D", "F", "A"),
t3 = c("C", "A", "E", "D"), stringsAsFactors = FALSE
)
clusters <- list(C1 = c("A", "B"), C2 = c("C", "D"), C3 = c("E", "F"))
net <- as_htna(seqs, clusters)
net
if (requireNamespace("cograph", quietly = TRUE)) cograph::plot_htna(net)
Convert a network comparison to a difference network
Description
as_netdifference() turns the result of a network comparison into a
plain netdifference object, the signed difference network that
subtract_networks() returns, so that cograph's difference renderer
draws it. It reads a bayes_compare() result (net_bayes), and returns
a netdifference unchanged. The drawn weights are the posterior mean
differences, by default only those of the credible edges, while the full
difference, its credible intervals and its probabilities of direction
are kept beside them.
Usage
as_netdifference(x, ...)
## S3 method for class 'net_bayes'
as_netdifference(x, significant_only = TRUE, ...)
## S3 method for class 'netdifference'
as_netdifference(x, ...)
## Default S3 method:
as_netdifference(x, ...)
Arguments
x |
The comparison: a |
... |
Not used. |
significant_only |
For a |
Value
A netdifference object, which is also a netobject (method
"difference"); print() lists its edges and cograph::splot() draws
it. From a net_bayes, its weights are the posterior mean
differences (all of them, or only the credible ones, by
significant_only), and it keeps the full posterior mean difference
(difference_matrix), the two posterior mean matrices (x, y), the
interval bounds (ci_lower, ci_upper), the Bayesian p-equivalents
(p_values), the probabilities of direction (p_difference), the
credibility matrix (sig), significant_only, and
netdifference_type = "bayes_compare".
Examples
s1 <- data.frame(V1 = c("A", "B", "C"), V2 = c("B", "C", "A"))
s2 <- data.frame(V1 = c("A", "C", "B"), V2 = c("C", "B", "A"))
b <- bayes_compare(build_network(s1, method = "relative"),
build_network(s2, method = "relative"),
draws = 200, seed = 1)
as_netdifference(b, significant_only = FALSE)
Convert a network from another package to a netobject
Description
as_netobject() converts a psychnets result (class
c("psychnet", "cograph_network")) or any bare cograph_network into the
c("netobject", "cograph_network") object the rest of Nestimate reads, so
it can be passed to net_centrality() and the other verbs that read a
network. The resampling verbs (bootstrap_network(),
network_reliability()) need the source data, which a psychnets result
does not carry, so build the network with build_network() for those. A
netobject is returned unchanged.
Usage
as_netobject(x)
## S3 method for class 'netobject'
as_netobject(x)
## S3 method for class 'psychnet'
as_netobject(x)
## S3 method for class 'cograph_network'
as_netobject(x)
## Default S3 method:
as_netobject(x)
Arguments
x |
The network to convert: a |
Details
For a psychnet, the edge table is rebuilt with integer node indices (a
psychnet stores character-labelled edges), the estimator name is kept
in method, and every field specific to the psychnet, including the
graphical-lasso kkt optimality certificate, is kept in the psychnet
entry of meta, so nothing is lost in the conversion.
For a bare cograph_network, the method is read from the tna entry of
its meta; without one, a symmetric weight matrix is taken as
"co_occurrence" and any other as "relative". A missing directed
field is read as TRUE. Numeric state codes in the stored data of a
converted tna model are decoded to their labels.
For a tna model (package tna), the network is rebuilt with
build_network() from the sequences the model carries, with the method
and the parameters stored in its attributes (type, params), and used
only when the rebuilt weights equal the model's own. It then behaves as
any network built from those sequences, in the resampling verbs too. A
model that cannot be reproduced that way (scaled weights, no sequence
data, or a type or parameter build_network() does not reproduce)
becomes a network of its weights without sequence data: verbs that only
read weights accept it, and verbs that resample or read sequences raise
an error of class nestimate_tna_unrebuilt that names the reason. A pruned
model keeps its data, and Nestimate reads the data: it converts to the
full network, with a warning of class nestimate_tna_pruned. A
group_tna gives a netobject_group, one network per group, named as
the groups are. The covariates the model keeps become the network's
metadata: actor is read from the metadata the model keeps
(attr(model$data, "meta"), kept when the model is built from
tna::prepare_data()); a model without it raises
nestimate_actor_missing. Every verb
that takes a network applies this conversion itself, so calling
as_netobject() first is not needed.
Value
A netobject (class c("netobject", "cograph_network")), read by
the same verbs as one from build_network(); validate_netobject()
checks its structure. For a group_tna: a netobject_group, a named
list with one such netobject per group.
Note
The idiographic package exports a function with the same
name. With both packages attached, the one attached last masks the
other; write Nestimate::as_netobject() to call this one.
See Also
Examples
net <- build_cor(data.frame(a = rnorm(50), b = rnorm(50), c = rnorm(50)))
identical(as_netobject(net), net) # netobjects pass through unchanged
Convert a psychometric MCML fit to a group of networks
Description
as_networks() gathers the cluster-level (macro) network and the
within-cluster networks of a build_mcml_pc() fit into one
netobject_group, so they go through the same verbs as any other group of
networks: print(), summary(), net_centrality(), and
cograph::splot() for drawing. It is the psychometric-network
counterpart of as_tna().
as_tna() converts transition networks (directed, row-normalised,
with initial probabilities) and re-wraps raw matrices. The macro and
within-cluster networks of an mcml_pc object are already full
netobjects of psychometric networks (undirected; correlation,
partial correlation or glasso) carrying their estimator and directedness,
and their data when they were re-estimated, so as_networks() only
assembles them into a group.
Usage
as_networks(x)
## S3 method for class 'mcml_pc'
as_networks(x)
## Default S3 method:
as_networks(x)
Arguments
x |
The object to convert: an |
Value
A netobject_group, which net_centrality() and cograph::splot() read as any group of networks: a named list whose first element, macro, is the cluster-level network, followed by one
netobject per cluster with more than one member. A singleton cluster has no within-cluster network
and is left out, with a warning naming it.
See Also
build_mcml_pc to create the input,
as_tna for the transition-network counterpart.
Examples
set.seed(1)
f <- stats::rnorm(200)
g <- stats::rnorm(200)
df <- data.frame(a1 = f + stats::rnorm(200), a2 = f + stats::rnorm(200),
a3 = f + stats::rnorm(200), b1 = g + stats::rnorm(200),
b2 = g + stats::rnorm(200), b3 = g + stats::rnorm(200))
clusters <- list(A = c("a1", "a2", "a3"), B = c("b1", "b2", "b3"))
fit <- build_mcml_pc(df, clusters, aggregation = "composite", method = "cor")
nets <- as_networks(fit)
nets
summary(nets)
Convert the layers of an MCML model to a group of networks
Description
as_tna() turns an mcml object into a netobject_group: one network
for the cluster-level (macro) layer, followed by one per cluster for the
within-cluster layers. The stored weights are carried over as they are –
nothing is re-normalised – so the networks hold the aggregation and
type chosen when the mcml was built. Despite its name it returns
Nestimate networks, not tna models; a tna model passed to it is
returned unchanged.
This is the step that lets an MCML result reach the verbs that take a
group of networks: printing, the network metrics of summary(),
bootstrap_network() (for an mcml built from sequences, whose layers
keep them; the layers of a cluster_summary() result carry none) and
drawing with cograph.
Usage
as_tna(x, ...)
## S3 method for class 'mcml'
as_tna(x, expand = NULL, ...)
## Default S3 method:
as_tna(x, ...)
Arguments
x |
An |
... |
Not used. |
expand |
For the |
Details
Workflow
# Full MCML workflow net <- build_network(data, method = "relative") cs <- cluster_summary(net, clusters = group_assignments) nets <- as_tna(cs) # Every layer is an ordinary netobject print(nets) # one line per layer summary(nets) # network metrics per layer
Sink nodes
Every cluster is returned, whatever its row sums. A node with no outgoing
weight is a legitimate sink (a terminal state), and its row stays all
zero in the network, for method = "relative" and "frequency" alike:
the stored weights are never re-normalised, so a sink row needs no
special handling.
Value
A netobject_group: a named list whose first element, macro, is
the k x k cluster-level network, followed by one network per cluster.
Print it for one row per layer (nodes, edges, weight range), call
summary() for the network metrics of each layer, and draw a layer
with cograph::splot(). Each
element is a netobject (class c("netobject", "cograph_network"))
with the layer's weights, initial probabilities, node and edge tables
and data, and records method = "relative" when the mcml holds
row-normalised weights (type = "tna") and method = "frequency" for
counts (type "raw", "frequency" or "cooccurrence") and for the
aggregates of cluster_summary(). An undirected mcml (type = "cooccurrence" or directed = FALSE) also records
params$symmetrize = TRUE, and one built from a weighted edge list
carries the edge weights in its data, so the resampling verbs recount
each layer as it was fitted. An mcml built with a method other
than "sum" records it as params$aggregation, so
bootstrap_network() combines the transitions of each resample the
same way. With
expand, the macro element is the mixed-resolution network of
macro_network() instead of the fully collapsed one. The default
method returns a tna model unchanged and raises an error for any
other class.
See Also
cluster_summary and build_mcml to create the
input object,
macro_network for a macro layer with one cluster expanded,
as_networks for the psychometric-network counterpart
Examples
set.seed(1)
mat <- matrix(runif(36), 6, 6)
rownames(mat) <- colnames(mat) <- LETTERS[1:6]
clusters <- list(G1 = c("A", "B"), G2 = c("C", "D"), G3 = c("E", "F"))
cs <- cluster_summary(mat, clusters)
nets <- as_tna(cs)
nets
summary(nets)
Discover association rules in transactions or sequences
Description
association_rules() finds association rules of the form
{A} -> {B} with the Apriori algorithm (Agrawal & Srikant, 1994): sets
of items that occur together in at least min_support of the
transactions, and the rules among them that pass min_confidence and
min_lift. It reads a list of transactions, a wide data frame or matrix of
states, a 0/1 incidence table, or a network: the sequences behind a
netobject or tna model become transactions of their distinct states,
and a one-hot network's windows become transactions of their active codes.
Support is how common the whole rule is, confidence how often B occurs
when A does, and lift how much more often A and B occur together than they
would if they were independent (see Metrics). A sequence read as a
transaction loses its order, so a rule says that states occur in the same
sequence, not that one follows the other; build_network() models order.
The rules are not tested for significance, and lowering the thresholds
quickly multiplies them, so check whether a rule of interest stays when
min_support changes.
Usage
association_rules(
x,
min_support = 0.1,
min_confidence = 0.5,
min_lift = 1,
max_length = 5L,
format = c("auto", "binary")
)
## S3 method for class 'net_association_rules'
print(x, ...)
## S3 method for class 'net_association_rules'
summary(object, ...)
## S3 method for class 'net_association_rules'
plot(x, ...)
Arguments
x |
The transactions, in one of these forms:
Binary input must hold only 0/1 or |
min_support |
The smallest share of transactions an itemset must
occur in to be frequent, above 0 and at most 1. Default |
min_confidence |
The smallest confidence a rule must have, between
0 and 1. Default |
min_lift |
The smallest lift a rule must have, at least 0. Default
|
max_length |
The largest itemset size searched, at least 2. Default
|
format |
How 0/1 columns are read. Columns of only 0 and 1 could be
items or recoded positions, so with |
... |
For the |
object |
For the |
Details
Algorithm
Level-wise Apriori (Agrawal & Srikant, 1994) with the full pruning step:
after the join step generates the candidates of size k, every subset of
size k - 1 is checked to be frequent before support is counted, which
keeps the search fast at k >= 4. Support of pairs is counted with
crossprod(), of larger itemsets by logical indexing. Every split of a
frequent itemset into a non-empty antecedent and consequent is a
candidate rule.
Metrics
- support
P(A and B): the share of transactions holding both the antecedent and the consequent.
- confidence
P(B | A): the share of transactions holding the antecedent that also hold the consequent.
- lift
P(A and B) / (P(A) P(B)). Values above 1 indicate positive association, below 1 negative association.
- conviction
(1 - P(B)) / (1 - confidence), the departure from independence in the direction of the rule (Brin et al., 1997); higher means a stronger implication, and a rule with confidence 1 has conviction
Inf.
Value
A net_association_rules object. print() shows the counts, the
thresholds and the ten rules with the highest lift; summary() returns
the rules table, one row per rule; plot() draws the rules by support
and confidence. The object's fields:
- rules
Data frame, one row per rule, ordered by decreasing lift and then confidence, with columns
antecedentandconsequent(the itemsets as comma-separated strings),support,confidence,lift,conviction,count(transactions holding the whole rule) andn_transactions.- frequent
Data frame, one row per frequent itemset, with columns
itemset,size,supportandcount.- frequent_itemsets
List of the frequent itemsets per size k, each entry a list of
items,countandsupport.- items
Character vector of the frequent single items the mining ran on (all items when none reaches
min_support).- n_transactions
Number of transactions.
- n_rules
Number of rules.
- params
List of
min_support,min_confidence,min_liftandmax_length.
The print() method returns its input invisibly. summary()
returns the rules data frame described above. plot() prints a scatter
plot of support against confidence, with point size and colour showing
lift, and returns the ggplot object invisibly; with no rules it says so
in a message and returns NULL invisibly.
References
Agrawal, R. & Srikant, R. (1994). Fast algorithms for mining association rules. In Proc. 20th VLDB Conference, 487–499.
Brin, S., Motwani, R., Ullman, J. D. & Tsur, S. (1997). Dynamic itemset counting and implication rules for market basket data. In Proc. ACM SIGMOD, 255–264. (lift and conviction)
See Also
Examples
# From a list of transactions
trans <- list(
c("plan", "discuss", "execute"),
c("plan", "research", "analyze"),
c("discuss", "execute", "reflect"),
c("plan", "discuss", "execute", "reflect"),
c("research", "analyze", "reflect")
)
rules <- association_rules(trans, min_support = 0.3, min_confidence = 0.5)
print(rules)
# From a netobject (sequences as transactions)
seqs <- data.frame(
V1 = sample(LETTERS[1:5], 50, TRUE),
V2 = sample(LETTERS[1:5], 50, TRUE),
V3 = sample(LETTERS[1:5], 50, TRUE)
)
net <- build_network(seqs, method = "relative")
rules <- association_rules(net, min_support = 0.1)
Compare two transition networks with a Bayesian Dirichlet model
Description
bayes_compare() compares two transition networks edge by edge and
returns, for every transition, the posterior mean difference in
transition probability, a credible interval, and the probability that
the difference lies on its side of zero. The transitions out of each
state are modelled as a multinomial draw with a Dirichlet prior on the
transition probabilities, so the posterior for the transitions out of
state i is \mathrm{Dirichlet}(c_i + \alpha), where c_i are the observed outgoing counts and
\alpha is prior. Each edge probability is then marginally
Beta-distributed: the posterior mean difference has a closed form, and
the credible interval comes from Monte Carlo draws. It takes two networks
estimated by build_network() with method "relative" or "frequency"
(for either, the difference is in transition probabilities estimated from
the counts), a group of networks, or two edge-betweenness networks from
net_edge_betweenness() (see
Details). An mcml object raises an error of class
nestimate_bad_input: its layers hold different states and carry no
transition counts.
The comparison complements permutation(): the permutation test asks
whether a difference is more extreme than chance, and this comparison
gives the plausible range of the difference and how precisely the counts
estimate it. An edge whose source state has few outgoing transitions gets
a wide interval even when its row-normalised probabilities look far
apart. An edge is flagged as credibly different when its interval
excludes zero and its mean and nearest bound pass mean_threshold and
bound_threshold; the thresholds are conventions, and no correction is
made for comparing many edges at once. The reported p_value (the
Bayesian p-equivalent 2(1 - p_d), with p_d
the probability of direction) summarises posterior mass and is not a
frequentist p-value. The model treats every transition as an independent
draw, so it does not account for transitions being nested in sequences,
which a permutation of sequences with permutation() respects.
Usage
bayes_compare(
x,
y = NULL,
prior = 0.5,
draws = 10000L,
ci = 0.95,
mean_threshold = 0.01,
bound_threshold = 0.001,
seed = NULL
)
## S3 method for class 'net_bayes'
print(x, ...)
## S3 method for class 'net_bayes'
summary(object, ...)
## S3 method for class 'net_bayes'
plot(x, significant_only = TRUE, title = NULL, ...)
## S3 method for class 'net_bayes_group'
print(x, ...)
## S3 method for class 'net_bayes_group'
plot(x, significant_only = TRUE, title = NULL, ...)
## S3 method for class 'net_bayes_group'
summary(object, ...)
Arguments
x |
The first network: a |
y |
The second network, of the same kind as |
prior |
The Dirichlet concentration added to every cell of the
count matrices, a positive number. Default |
draws |
The number of Monte Carlo posterior draws behind the
credible intervals, at least 2. Default |
ci |
The mass of the equal-tailed credible interval, a number
between 0 and 1. Default |
mean_threshold |
The absolute posterior mean difference an edge
must exceed to be flagged as credibly different. Default |
bound_threshold |
The absolute value the interval bound nearest
zero must exceed for an edge to be flagged. It guards against
differences that are detectable but negligibly small. Default |
seed |
An integer that makes the draws reproducible; the session's
own random stream is left as it was.
Default |
... |
For |
object |
For |
significant_only |
For |
title |
For |
Details
For two net_edge_betweenness objects (source method "relative"
only), edge betweenness is a nonlinear function of the whole transition
matrix, so Beta marginals do not apply. Instead the full transition
matrix is drawn from each network's row-wise Dirichlet posterior and edge
betweenness is recomputed on every draw, the Bayesian analogue of
permutation() on edge-betweenness networks. The result summarises the
posterior of EB(x) - EB(y): diff is the posterior mean
difference, prob_x and prob_y the posterior mean betweenness
matrices, and observed_diff the plug-in difference of the two input
networks. Both inputs must use the same invert setting, and
mean_threshold and bound_threshold are then on the betweenness
scale.
Value
A net_bayes object (class
c("net_bayes", "netdifference", "net_permutation")), or, for a
netobject_group input, a net_bayes_group: a list of net_bayes
objects named by comparison ("A vs B"), or by group name when two
groups are compared. print() shows the method, the prior, draws,
interval and thresholds, and the numbers of nodes, of edges compared
and of edges credibly different (for a group, it lists the
comparisons); summary() returns one row per edge observed in
at least one network (for a group, with a comparison column); and
plot() draws the difference network. A net_bayes carries the same
fields as a permutation() result, so it is accepted wherever a
net_permutation is, and also carries a difference matrix for the
netdifference verbs (as_netdifference(), cograph's difference
plots). Its fields:
- x, y
The two input networks.
- diff
Posterior mean difference matrix (
prob_x - prob_y); the analogue of the permutation test's observed difference.- difference_matrix
The same matrix as
diff, for cograph'snetdifferencehelpers.- diff_sig
The difference where
sigisTRUE, else 0.- p_values
The two-sided Bayesian p-equivalent, in the field a
net_permutationconsumer reads as p-values (seep_bayes).- effect_size
Posterior mean difference over its posterior standard deviation (0 where that is 0).
- ci_lower, ci_upper
Credible-interval bound matrices.
- p_difference
Probability of direction: the share of posterior mass on the dominant side of zero, in
[0.5, 1].- p_bayes
The same matrix as
p_values: the two-sided Bayesian p-equivalent2(1-\mathrm{p\_difference}). It summarises posterior mass, not a frequentist tail probability, so it is not a p-value and should not be reported as one.- prob_x, prob_y
Posterior mean transition-probability matrices (posterior mean betweenness for edge-betweenness input).
- sig
Logical matrix: the interval excludes zero and the mean and nearest bound exceed their thresholds.
- summary
The per-edge table that
summary()returns, with the columns of anet_permutationsummary (from,to,weight_x,weight_y,diff,effect_size,p_value,sig) pluscount_x,count_y,ci_lower,ci_upper,ci_widthandp_difference.- method, iter, alpha, paired, adjust
Permutation-compatible settings (
iter = draws,alpha = 1 - ci,paired = FALSE,adjust = "none");methodis"edge_betweenness"for edge-betweenness input.- prior, draws, ci, mean_threshold, bound_threshold
The Bayesian settings.
- observed_diff, source_method, edge_betweenness
For edge-betweenness input only: the plug-in difference, the source networks' method and the betweenness settings.
For the print() methods: the input, invisibly. For summary():
the per-edge data frame described under the summary field; for a
net_bayes_group, the tables of every comparison stacked, with a
comparison column first. For plot(): with cograph installed, it
draws the difference network with cograph::splot(), each edge
labelled with its posterior mean difference and credible interval,
blue (#4A6FE3) where x is higher and red (#D33F6A) where y is
(edge_positive_color and edge_negative_color change them), and
returns the cograph_network invisibly; without cograph, it returns a
ggplot chord diagram in which colour gives the direction of the
difference and width its size. For a net_bayes_group, plot() draws
every comparison in turn, each titled with its name, and returns their
results in a list named by comparison, invisibly; a group of one
comparison returns that comparison's result.
References
Johnston, L. & Jendoubi, T. (2026). How Delivery Mode Reshapes Resource Engagement: A Bayesian Differential Network Analysis. TNA Workshop 2026.
Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., & Rubin, D. B. (2013). Bayesian Data Analysis (3rd ed.). CRC Press.
Jeffreys, H. (1946). An invariant form for the prior probability in estimation problems. Proceedings of the Royal Society of London A, 186(1007), 453-461.
See Also
permutation for the frequentist complement;
certainty for single-network posterior edge intervals;
subtract_networks and as_netdifference for the
difference verbs; build_network
Examples
s1 <- data.frame(V1 = c("A","B","C"), V2 = c("B","C","A"))
s2 <- data.frame(V1 = c("A","C","B"), V2 = c("C","B","A"))
n1 <- build_network(s1, method = "relative")
n2 <- build_network(s2, method = "relative")
bayes_compare(n1, n2, draws = 200, seed = 1)
Count the holes of a simplicial complex
Description
betti_numbers() counts the holes of a simplicial complex in each
dimension: \beta_0 is the number of connected components,
\beta_1 the number of independent loops (cycles not filled in by
triangles), \beta_2 the number of enclosed voids, and so on up to
the dimension of the complex.
Betti numbers describe the complex as it was built; a clique complex
built at a different threshold can give different numbers.
persistent_homology() follows each hole across all thresholds and shows
how long it lasts.
Usage
betti_numbers(sc)
Arguments
sc |
A |
Details
\beta_k is the dimension of the k-th homology group, the number of
k-simplices minus the rank of the k-th boundary matrix, minus the rank of
the (k + 1)-th. The ranks are computed with qr() on the signed boundary
matrices.
Value
A named integer vector c(b0 = , b1 = , ...), one entry per
dimension from 0 to the dimension of the complex.
Examples
mat <- matrix(c(0,.6,.5,.6,0,.4,.5,.4,0), 3, 3)
colnames(mat) <- rownames(mat) <- c("A","B","C")
sc <- build_simplicial(mat, threshold = 0.3)
betti_numbers(sc)
Build a hypergraph from group memberships
Description
bipartite_groups() builds a hypergraph from long-format membership
data, in which each row records that a player took part in a group
(a session, team, project, transaction or any other group context), and
returns a net_hypergraph. Each distinct group becomes one hyperedge
spanning the players that appeared in it. The incidence matrix of
players by groups is 0/1, or holds summed weights when weight is
given.
Usage
bipartite_groups(data, player, group, weight = NULL)
Arguments
data |
A data frame with one row per membership (a player in a
group), holding the |
player |
The name of the column whose values become the nodes
(players, participants, actors). Values are read as character and the
nodes are sorted. A name that is not a single column of |
group |
The name of the column whose values become the hyperedges
(groups, sessions, teams). Values are read as character, and the
hyperedges follow their sorted order (as text, so |
weight |
The name of a numeric column summed per player and group
to give a weighted incidence matrix. With the default |
Details
The bipartite representation preserves the full group structure without projecting to a pairwise network. A group of three players A, B, C produces a single 3-hyperedge containing all three, not three pairwise edges AB, AC, BC. This avoids information loss when group interactions are the primary unit of analysis (Perc et al. 2013).
bipartite_groups() takes group memberships as observed, while build_hypergraph() infers groups from the cliques of a network. The two functions are complementary:
-
bipartite_groups()- when group membership is observed (sessions, transactions, co-authorships). -
build_hypergraph()- when only pairwise interactions are observed and group structure must be inferred from cliques (triangles by default).
Value
A net_hypergraph, the class build_hypergraph() returns. Print
it for the numbers of nodes and hyperedges and the hyperedge sizes;
summary() prints the counts with the mean and largest hyperedge size,
and returns a data frame of node degrees (node, and degree, the
number of hyperedges a player belongs to). hypergraph_measures(),
hypergraph_centrality(), hypergraph_laplacian() and
hypergraph_cluster() read it. The fields:
- hyperedges
An unnamed list with one vector per hyperedge, in the sorted order of the groups: the indices of its players in
nodes, sorted and named by player.- incidence
The players-by-groups matrix, one column per hyperedge, with player and group names as dimnames: integer 0/1, or the summed weights (a player whose sum is zero or negative keeps that sum here but is not a member of the hyperedge).
- nodes
The player names, sorted.
- n_nodes, n_hyperedges
The numbers of players and of hyperedges (after dropping empty groups).
- size_distribution
A named integer vector with the number of hyperedges of each size (
size_1,size_2, ...).- params
A list with
source = "bipartite_groups", the column names given asplayer,groupandweight, andn_observations, the number of rows used.
Note
(experimental) Validated against a hand-computed table() incidence
reference only; no independent R package exposes the
long-format-to-binary-incidence primitive, because the operation is
definitionally table(). The code path is a direct one-to-one
restatement of its definition.
References
Perc, M., Gomez-Gardenes, J., Szolnoki, A., Floria, L. M., & Moreno, Y. (2013). Evolutionary dynamics of group interactions on structured populations: a review. Journal of the Royal Society Interface 10(80), 20120997. doi:10.1098/rsif.2012.0997
See Also
build_hypergraph() for the clique-based constructor.
Examples
df <- data.frame(
player = c("Alice", "Bob", "Carol", "Alice", "Bob",
"Dave", "Carol", "Dave", "Eve"),
session = c("S1", "S1", "S1", "S2", "S2",
"S3", "S3", "S3", "S3")
)
hg <- bipartite_groups(df, player = "player", group = "session")
print(hg)
summary(hg)
Bootstrap a graphical lasso network
Description
boot_glasso() assesses how accurately an EBIC graphical lasso network
is estimated and how stable its centralities are, by resampling the
observations (Epskamp, Borsboom & Fried, 2018). One call runs a
nonparametric bootstrap, which gives percentile intervals and inclusion
probabilities for every edge, intervals for each node's centralities and
predictability, and bootstrap tests of the difference between every pair
of edges and every pair of nodes; and a case-dropping bootstrap, which
gives each centrality measure's correlation-stability (CS) coefficient.
It takes the raw data or a network built with method = "glasso".
An interval shows how precisely an edge weight is estimated: a wide one
means the weight changes a good deal between samples. Epskamp et al.
(2018) caution that, because the lasso shrinks estimates towards zero,
these intervals are not tests of whether an edge differs from zero; the
thresholded network (edges whose interval excludes zero) and the
"significant" count in print() read them that way, and the inclusion
probability (how often an edge is non-zero across resamples) is a
separate summary. The CS-coefficient is the largest proportion of cases
that can be dropped while more than 95% of the subsamples keep a
correlation above 0.7 with the original centralities; Epskamp et al.
(2018) suggest it should not be below 0.25 and preferably above 0.5
before the centrality order is interpreted, and print() labels the
values accordingly. The difference tests are not corrected for the
number of pairs compared.
Usage
boot_glasso(
x,
iter = 1000L,
cs_iter = 500L,
cs_drop = seq(0.1, 0.9, by = 0.1),
alpha = 0.05,
gamma = 0.5,
nlambda = 100L,
centrality = c("strength", "expected_influence", "betweenness", "closeness"),
centrality_fn = NULL,
cor_method = "pearson",
ncores = 1L,
seed = NULL
)
## S3 method for class 'boot_glasso'
print(x, ...)
## S3 method for class 'boot_glasso'
summary(object, type = "edges", ...)
## S3 method for class 'boot_glasso'
plot(x, type = "edges", measure = NULL, ...)
Arguments
x |
The data: a data frame or numeric matrix with one row per
observation and one column per variable, cleaned as in
|
iter |
The number of nonparametric bootstrap resamples, at least 2.
Default |
cs_iter |
The total number of case-dropping iterations, at
least 1. Default |
cs_drop |
The proportions of cases to drop, each in (0, 1). Default
|
alpha |
The significance level: the intervals run from the
|
gamma |
The EBIC hyperparameter; larger values give sparser
networks. Default |
nlambda |
The number of lambda values in the regularisation path,
at least 2. Default |
centrality |
The centrality measures to compute. Default all four
built-in ones: |
centrality_fn |
A function for measures beyond the four built-in
ones: it takes the partial correlation matrix and returns a named list of centrality vectors, such as
|
cor_method |
The correlation method: |
ncores |
The number of cores for the resampling, used through
|
seed |
A seed for reproducible resampling; the session's random
state is restored when the call returns. Default |
... |
For the |
object |
For the |
type |
What to return or draw. For the |
measure |
For the |
Details
The network is estimated as build_glasso() estimates it: with a
netobject, with its own params (lambda.min.ratio,
penalize.diagonal, refit); with data, with that function's defaults
(smallest lambda 0.01 times the largest, no penalty on the diagonal, the
selected penalty re-solved exactly, no unregularised refit). The lambda
path is set once from the original data and reused for every resample,
which is fitted with the same settings; the penalty is chosen on it by
EBIC with gamma. Strength is the sum of a node's absolute edge weights and
expected influence the sum of its signed weights; betweenness and
closeness use shortest paths with distance 1 / |weight|, computed
without igraph. Predictability is 1 - 1 / \Theta_{ii}, from the
diagonal of the precision matrix, bounded to 0–1.
The case-dropping bootstrap follows bootnet: each of the cs_iter
iterations draws one proportion from cs_drop at random, keeps that
share of the rows (at least p + 1 of them) without replacement, and
correlates the subsample's centralities with the original ones; a
centrality that is constant across nodes counts as a correlation of 0.
The difference tests give, for each pair, the two-sided bootstrap p-value
2 * min(P(d >= 0), P(d <= 0)) of the difference d between the two
edges or nodes, capped at 1, with ties counted in both tails. The
edge-difference test is skipped for networks with more than 500 edges. A
resample whose estimation fails (for example, a variable constant in the
resample) is kept as missing and left out of the intervals and the
case-dropping results; the failures are counted in n_failed and
cs_n_failed, shown by print(), and reported in a warning of class
nestimate_resample_failed. The function was written as a faster, single-call
alternative to running bootnet several times.
Value
A boot_glasso object. print() reports the data size,
alpha and gamma, the number of edges whose interval excludes zero,
the mean inclusion probability, the failed resamples when there are
any, each measure's CS-coefficient with its
label, the number of edge pairs that differ, and the timing;
summary() returns the table chosen by type (edges, centralities,
case-dropping results or predictability; described at the end of this
section); plot() draws one figure chosen by type. The object's
fields:
- original_pcor
The partial correlation matrix of the original data.
- original_precision
The precision matrix of the original data.
- original_centrality
A named list with one vector of node values per centrality measure.
- original_predictability
A named vector of each node's R-squared.
- edge_ci
A data frame with one row per edge:
edge,weight,ci_lower,ci_upperandinclusion.- edge_inclusion
A named vector of edge inclusion probabilities.
- thresholded_pcor
The partial correlation matrix with every edge whose interval includes zero set to zero.
- centrality_ci
A named list with one data frame per centrality measure:
node,value,ci_lower,ci_upper.- cs_coefficient
A named vector with the CS-coefficient of each centrality measure.
- cs_data
A data frame of the case-dropping results, one row per drop proportion and measure:
drop_prop,measure,mean_cor,prop_above(the share of that proportion's iterations correlating above 0.7) andn_samples(the iterations that drew that proportion).- edge_diff_p
A symmetric matrix of the edge-difference p-values;
NULLwhen the network has more than 500 edges.- centrality_diff_p
A named list with one symmetric matrix of node-difference p-values per centrality measure.
- predictability_ci
A data frame with one row per node:
node,r2,ci_lower,ci_upper.- boot_edges
An
iterx edges matrix of the bootstrap edge weights.- boot_centrality
A named list with one
iterx nodes matrix of bootstrap values per centrality measure.- boot_predictability
An
iterx nodes matrix of bootstrap R-squared values.- nodes
The node names.
- n
The sample size.
- p
The number of variables.
- iter, cs_iter, cs_drop, alpha, gamma, nlambda
The settings used.
- centrality_measures
The centrality measures computed.
- cor_method
The correlation method used.
- lambda_path
The lambda path used for every fit.
- lambda_selected
The lambda selected on the original data.
- n_failed, cs_n_failed
The numbers of bootstrap and case-dropping resamples whose estimation failed and that were left out.
- timing
A named vector of elapsed seconds:
total,phase1(the original fit),bootstrap,case_dropandstatistics.
print() returns its input invisibly. summary() returns a data
frame: for type = "edges" the edge_ci table (edge, weight,
ci_lower, ci_upper, inclusion) sorted by decreasing absolute
weight, for "cs" the cs_data table and for "predictability" the
predictability_ci table; "centrality" returns a named list with one
data frame per measure (node, value, ci_lower, ci_upper), and
"all" a named list of the four (edges, centrality, cs,
predictability). plot() returns a ggplot object, which is drawn
when the call is made at the top level. The edge-difference plot raises
an error when the test was skipped (more than 500 edges).
Methods
-
plot()draws one figure of the bootstrap results per call, chosen withtype.
References
Epskamp, S., Borsboom, D., & Fried, E. I. (2018). Estimating psychological networks and their accuracy: A tutorial paper. Behavior Research Methods 50(1), 195-212. doi:10.3758/s13428-017-0862-1 (source of the CS-coefficient and of the case-dropping, edge-difference and centrality-difference procedures reproduced here.)
See Also
build_network, bootstrap_network
Examples
set.seed(1)
dat <- as.data.frame(matrix(rnorm(60), ncol = 3))
net <- build_network(dat, method = "glasso")
bg <- boot_glasso(net, iter = 10, cs_iter = 5, centrality = "strength")
set.seed(42)
mat <- matrix(rnorm(60), ncol = 4)
colnames(mat) <- LETTERS[1:4]
net <- build_network(as.data.frame(mat), method = "glasso")
# iter = 20 keeps the example fast; a real analysis uses 1000 or more.
boot <- boot_glasso(net, iter = 20, cs_iter = 10, seed = 42,
centrality = c("strength", "expected_influence"))
print(boot)
summary(boot, type = "edges")
Bootstrap a network estimate
Description
bootstrap_network() resamples the cases a network was estimated from,
re-estimates the network on every resample with the same method and
settings, and reports for each edge its bootstrap mean, standard
deviation, confidence interval and a p-value, together with the network
pruned to the edges that pass. It reads any network from
build_network(), built-in method or registered estimator, as well as a
netobject_group or mcml (every network is bootstrapped) and a
wtna_mixed (both of its components). The cases are the sequences of a
transition network (for one-hot data, its actors or sessions) and the
rows of the data otherwise; with actor, whole actors are resampled (see
Nested data and actor).
The p-value comes from one of two tests. With inference = "stability"
it counts the replicates that fall outside a consistency range around
the original weight (by default 75% to 125% of it), so a significant edge
is one whose weight the resamples reproduce within that range. With
inference = "threshold" it counts the replicates whose absolute weight
falls below edge_threshold, so a significant edge stays above that
threshold. In both, the p-value is that count plus one, divided by the
number of replicates plus one, so it is never 0. Edges with a p-value
below ci_level are kept in the pruned network.
The p-value counts replicates, so it cannot fall below
1 / (iter + 1): with too few iterations no edge can pass a small
ci_level. The stability test asks whether a weight is reproduced
within a range, not whether it differs from zero, and because the range
is a proportion of the weight, a weak edge has to be reproduced within a
narrow band; read the interval beside the test. The bootstrap describes
how the estimate varies over resamples of one sample; to compare groups,
use permutation().
Usage
bootstrap_network(
x,
iter = 1000L,
ci_level = 0.05,
inference = "stability",
consistency_range = c(0.75, 1.25),
edge_threshold = NULL,
seed = NULL,
boundary = c("inclusive", "strict"),
ci_method = c("percentile", "basic"),
actor = NULL
)
## S3 method for class 'net_bootstrap'
print(x, ...)
## S3 method for class 'net_bootstrap'
summary(object, ...)
## S3 method for class 'net_bootstrap_group'
print(x, ...)
## S3 method for class 'net_bootstrap_group'
summary(object, ...)
## S3 method for class 'wtna_boot_mixed'
print(x, ...)
## S3 method for class 'wtna_boot_mixed'
summary(object, ...)
Arguments
x |
The network: a |
iter |
The number of bootstrap replicates, at least 2. Default
|
ci_level |
The significance level, between 0 and 1: the confidence
intervals cover |
inference |
The test behind the p-values. |
consistency_range |
For |
edge_threshold |
For |
seed |
A number that makes the resamples reproducible. The session's
own random stream is left as it was. For a |
boundary |
For |
ci_method |
The confidence interval for the edge weights.
|
actor |
The column identifying the actor each sequence belongs to
(for example |
... |
For the |
object |
For the |
Details
The two tests and the inclusive boundary rule follow tna::bootstrap().
A latency network (method = "latency") is resampled by its sequences, and
every edge's weight is recomputed from the replies of the drawn sequences.
A percentile cap the network resolved from its own replies is resolved
again in every resample; a cap in seconds, or one pooled over the groups of
a grouped build, keeps its value. A resample whose resolved cap is 0
seconds (its replies mostly instant) stops the bootstrap with an error of
class nestimate_latency_zero_cap; give the cap in seconds. Per-unit caps (latency_scope other than
"global") and actor raise an error of class
nestimate_latency_resampling or nestimate_actor_unsupported; to resample
within groups, build the network with group and bootstrap the group. With
the default aggregate = "mean", the stability test is run on the speed
score (weight - floor) / (1 - floor), which runs from 0 (every reply at or
past the cap) to 1 (every reply instant), because a band around a mean
weight between the floor and 1 passes almost every edge. An edge whose
replies come from fewer than 5 sequences cannot vary across resamples and
gets a p-value of 1. The summary adds each edge's n_replies,
n_sequences and cv, the coefficient of variation of its resampled
speed scores. These rules were checked by simulation against known reply
speeds: with a percentile cap the 95% intervals covered 0.91-0.95 of the
true weights from 30 sequences on, and an edge called stable was within
25% of its true score in 97-100% of datasets from 300 sequences on.
Bootstrapping latency networks is experimental: every call says so in a
message of class nestimate_experimental (once for a group of networks).
Transition networks ("relative", "frequency", "co_occurrence", and
wtna networks, which hold the same one-hot counts) take a fast path:
the count matrix of every sequence is computed once, and each replicate
sums the counts of the sequences drawn, then applies the network's
normalisation, scaling and threshold. With params = list(concat = k),
the consecutive groups of up to k rows merged by the estimator are the
sequences resampled; joins inside each merged sequence are retained.
With actor, a merged sequence must belong entirely to one actor. Every
other method (the association methods, "attention", "ngram", "gap",
"reverse" and registered estimators) is re-estimated in full on
resampled rows. A replicate whose estimation fails, or
that loses a node, is left out of the p-values, with a warning of class
nestimate_resample_failed that counts them, and the bootstrap
statistics are computed over the remaining replicates; if every
replicate fails, every p-value is 1.
A network built from an edge list (for example an mcml from
build_mcml() with from and to) has no sequences, so each
transition is resampled as an independent case, with a warning of class
nestimate_edgelist_resampling that points to the alternatives. An
mcml built with a method other than "sum" (such as "mean" or
"max") combines the transitions of each resample by that method, so
every replicate is the mcml that build_mcml() gives on the resampled
rows; actor is then not supported and raises an error of class
nestimate_actor_unsupported.
Value
A net_bootstrap object. print() lists the five strongest
significant edges (by absolute bootstrap mean, with their interval)
and reports the iterations, the number of significant edges, the
interval level and the test, and with actor the ICC and design
effect; summary() returns one row per edge of the original network;
cograph::splot() draws the bootstrapped network; net_prune() with
method = "bootstrap" removes the non-significant edges from the
original network. The fields:
- original
The original
netobject.- mean, sd
The bootstrap mean and standard deviation of each weight, as matrices.
- p_values
The matrix of p-values.
- significant
The original weights where the p-value is below
ci_level, and 0 elsewhere, self-loops included.- ci_lower, ci_upper
The matrices of interval bounds.
- cr_lower, cr_upper
The matrices of consistency-range bounds (used by
"stability"only).- summary
A data frame with one row per non-zero original edge (one row per unordered pair in an undirected network) and the columns
from,to,weight,mean,sd,p_value,sig,ci_lowerandci_upper, pluscr_lowerandcr_upperwithinference = "stability".- model
The pruned
netobject, whose weights aresignificant: its non-significant edges, self-loops included, are zero. (The networknet_prune()returns keeps every self-loop.)- method, params, iter, ci_level, inference, ci_method
The bootstrap settings.
- consistency_range, edge_threshold
The test settings.
- actor, n_actors
The
actorcolumn (or columns, outermost first) and the number of actors resampled (at the outermost level);NULLwithoutactor.- clustering
Only with
actor: a one-row data frame ofn_sequences,n_actors,icc,icc_ci_lower,icc_ci_upperanddeff_edges.- clustering_edges
Only with
actor: one row per edge ofsummary, withfrom,to,icc,sd_actor,sd_sequenceanddeff.
A netobject_group or mcml gives a net_bootstrap_group, a named list
of net_bootstrap results: its print() reports each network's
significant and total edges and the significant edges all networks
share (when the networks have edges in common); its summary() is
described with the methods below. A wtna_mixed gives a
wtna_boot_mixed holding the transition and cooccurrence results.
The print() methods return their input invisibly. The
summary() method of a net_bootstrap returns its per-edge table, the
summary field described above. For a net_bootstrap_group
it returns the tables of all groups stacked into one data frame, with a
first column group naming the network each row comes from; the group
object keeps that table from the start (its "summary" attribute); for
a wtna_boot_mixed it
returns a list of the transition and cooccurrence tables.
Nested data and actor
The bootstrap resamples sequences as independent units. When sequences
are nested in actors (sessions in students, students in teams),
actor names the column identifying the actor, and whole actors
are resampled with replacement, keeping all their sequences together:
the cluster bootstrap that resamples at the top level only (Davison &
Hinkley, 1997, section 3.8; Field & Welsh, 2007). The number of
sequences per replicate then varies with the actors drawn.
Several columns, outermost first (actor = c("Group", "Student"), students
within teams), name nested levels. Every column is checked, but only the
outermost level is resampled: whole teams, each with all its students
and sessions. Resampling inside the drawn clusters as well (students
within teams) adds their variation a second time and overstates the
variance (Davison & Hinkley, 1997, section 3.8). The ICC and design
effect are then those of the outermost level, and print() names it as
the resampled level.
With actor, the result also reports the nesting effect. The ICC
is the proportion of the total variance that lies between actors (Shrout
& Fleiss, 1979); an ICC close to 0 indicates little evidence of a nesting
effect. It is computed as in permutation. The design effect
is the ratio of the variance under the nested design to the variance had
the sequences been sampled independently (Kish, 1965): here, the variance
of the edge weights over actor-level replicates divided by their variance
over sequence-level replicates drawn in the same run, reported as the
median over edges. actor is available for transition networks
("relative", "frequency", "co_occurrence").
When to set actor: resampling sequences describes the variability
of these actors' sequences; to generalise to other actors (other
students, other teams), resample actors. A drawn actor brings all of
their sequences, so a replicate can contain an actor twice or not at
all. The design effect, not the ICC alone, decides how much this
matters: Kish's approximation 1 + (m - 1) * ICC for clusters of m
equally informative units grows with the cluster size, so a small ICC
over large clusters still widens the intervals. In one data set of
sessions nested in students, the transitions of one student correlated
at about 0.01, yet with about 59 transitions per student (size-weighted
mean) the Rao-Scott design effect of the transition table was about 1.5
(mosaic_test()). The printed values, which take the sequence as the
unit, were an ICC of 0.05 and a design effect of 1.24; resampling
students gave intervals about a quarter wider than resampling sessions,
and fewer significant edges (18 against 22).
References
Davison, A. C., & Hinkley, D. V. (1997). Bootstrap Methods and Their Application. Cambridge University Press.
Field, C. A., & Welsh, A. H. (2007). Bootstrapping clustered data. Journal of the Royal Statistical Society: Series B, 69(3), 369-390.
Kish, L. (1965). Survey Sampling. Wiley.
Shrout, P. E., & Fleiss, J. L. (1979). Intraclass correlations: Uses in assessing rater reliability. Psychological Bulletin, 86(2), 420-428.
See Also
certainty for the closed-form Bayesian counterpart
(same result layout, no resampling);
build_network
Examples
net <- build_network(data.frame(V1 = c("A","B","C"), V2 = c("B","C","A")),
method = "relative")
boot <- bootstrap_network(net, iter = 10)
set.seed(1)
seqs <- data.frame(
V1 = sample(LETTERS[1:4], 30, TRUE), V2 = sample(LETTERS[1:4], 30, TRUE),
V3 = sample(LETTERS[1:4], 30, TRUE), V4 = sample(LETTERS[1:4], 30, TRUE)
)
net <- build_network(seqs, method = "relative")
boot <- bootstrap_network(net, iter = 20)
print(boot)
summary(boot)
# Students nested in teams: resample whole teams
teams <- build_network(group_regulation_long, method = "relative",
actor = "Actor", action = "Action", time = "Time",
group = "Achiever")
bootstrap_network(teams, iter = 20, actor = "Group", seed = 1)
Compute the bottleneck distance between persistence diagrams
Description
bottleneck_distance() returns the bottleneck distance between two
persistence diagrams, one value per homology dimension. It takes two
persistent_homology() results, or two data frames of persistence
pairs. For the finite pairs, the distance is
W_\infty(D_1, D_2) = \inf_{\gamma} \sup_{p \in D_1} \|p - \gamma(p)\|_\infty,
where \gamma ranges over bijections D_1 \cup \Delta \to
D_2 \cup \Delta and \Delta = \{(x,x)\} is the diagonal. Each
point is matched to a point of the other diagram or to its projection
onto the diagonal, at cost |d - b|/2.
The distance is the largest shift needed to match the two diagrams'
features: a small value means every feature of either diagram has a close
counterpart in the other or is short-lived enough to sit near the
diagonal. It is a distance between two observed diagrams and carries no
sampling uncertainty of its own; to compare diagrams on a common grid,
or to average several, use persistence_landscape().
Usage
bottleneck_distance(d1, d2, dimension = NULL, tol = .Machine$double.eps^0.5)
Arguments
d1, d2 |
The two diagrams: |
dimension |
The homology dimensions to compare, as whole numbers.
Default |
tol |
The tolerance added to each candidate cost when checking
whether a matching exists, so that floating-point error does not miss
an exact match. Default |
Details
The smallest feasible \varepsilon is found by binary search over
the candidate costs (every pairwise L_\infty distance and every
diagonal projection), checking each with a Kuhn bipartite matching.
Essential classes are matched one-to-one within each dimension by their sorted births. A class is essential when it never dies: death Inf in a Vietoris-Rips filtration, or death 0 with a positive birth in a clique filtration, as in persistence_landscape(). A (0, 0) pair is a finite point of length zero. When the two diagrams have different
numbers of essential classes in a dimension, the distance for that
dimension is Inf.
Value
A named numeric vector with one distance per dimension, named
"dim_<k>" (empty when there is no dimension to compare). Inf marks
a structural mismatch: different numbers of essential classes in that
dimension. The distance of a diagram to itself is 0.
References
Edelsbrunner, H. & Harer, J. (2010). Computational Topology: An Introduction. AMS. Section VIII.
Examples
mat1 <- matrix(c(0, .6, .5, .6, 0, .4, .5, .4, 0), 3, 3)
rownames(mat1) <- colnames(mat1) <- c("A","B","C")
ph1 <- persistent_homology(mat1, n_steps = 5)
bottleneck_distance(ph1, ph1) # self-distance is 0
Estimate an attention transition network analysis (ATNA) model
Description
build_network(method = "attention"), or for short build_atna(),
estimates an attention transition network analysis (ATNA) model, in which
every later state in a sequence counts, not only the next one. A pair of
positions d steps apart adds exp(-d / lambda) to the edge from the
earlier state to the later one, so near successors weigh most (Saqr et
al., 2025).
The weights are summed decay weights, not counts or probabilities, so
they compare within one network; add scaling = "normalize" for rows
that sum to 1. Attention networks read sequences and event logs, not
one-hot data.
Usage
build_atna(
data,
start = FALSE,
end = FALSE,
actor = NULL,
action = NULL,
time = NULL,
session = NULL,
...,
order = NULL,
time_threshold = 900,
timezone = "UTC",
state_cols = NULL,
metadata_cols = NULL,
lambda = 1,
direction = c("forward", "backward", "both"),
decay = NULL,
group = NULL,
scaling = NULL,
threshold = 0,
labels = NULL,
params = list()
)
Arguments
data |
The sequences: a data frame with one row per sequence and one
column per position, or an event log (one row per event, with |
start |
A start state put before every sequence, so the network
shows where sequences begin (an edge from it to each sequence's first
state). |
end |
An end state put in the cell after each sequence's last
observed state, so the network shows where sequences stop. It has no
outgoing edges and no self-loop, unlike |
actor |
The column naming who each row belongs to (a person, a
team). In an event log, each actor's events form a sequence, split
further by |
action |
The column holding each event's state; setting it declares
the data an event log. Column names give no role: |
time |
The timestamp column of an event log. Events are ordered by
it, and a gap longer than |
session |
The column identifying sessions in an event log; each
session is its own sequence, also without |
... |
Further arguments for |
order |
The column that orders events sharing a timestamp; without
it, those events keep their row order. Default |
time_threshold |
The longest gap, in seconds, between two events of
the same sequence in an event log; a longer gap starts a new sequence.
|
timezone |
The Olson time zone for timestamps without an offset
(passed to |
state_cols |
The columns of a wide table that are sequence
positions; every other column goes to the network's metadata. Declared
columns are positions even when they hold only 0 and 1. With nothing
declared, the frame must be one column or hold position columns named
as a numbered run (a shared prefix and a number, |
metadata_cols |
Columns to keep as the network's metadata
(covariates), never as positions; they cannot overlap |
lambda |
The decay length: larger values let distant states count
more. Default |
direction |
|
decay |
A function of |
group |
A column to split the data by: one network per value,
returned as a |
scaling |
Rescaling applied to the weights after estimation, in the
order given: |
threshold |
Weights whose absolute value is below this are set to
zero. Default |
labels |
New display labels for the nodes, applied after estimation:
a two-column data frame ( |
params |
Settings for the estimator, as a named list, as for
|
Value
A netobject (a netobject_group with group), as
build_network() returns it.
References
Saqr, M., López-Pernas, S., Törmänen, T., Kaliisa, R., Misiejuk, K., & Tikka, S. (2025). Transition network analysis: A novel framework for modeling, visualizing, and identifying the temporal patterns of learners and learning processes. In Proceedings of the 15th International Learning Analytics and Knowledge Conference (LAK25) (pp. 351–361). ACM. doi:10.1145/3706468.3706513
See Also
build_network() for every method; build_tna() for the
transitions to the next state only.
Examples
build_network(trajectories, method = "attention")
build_atna(trajectories)
build_atna(trajectories, lambda = 2, direction = "both")
Cluster sequences by dissimilarity
Description
build_clusters() splits a set of sequences into k groups of similar
sequences. It computes the dissimilarity between every pair of sequences
(the Hamming distance, an edit distance, a q-gram distance or the
Jaro-Winkler distance) and partitions that matrix with PAM (partitioning
around medoids) or a hierarchical method. It takes wide sequence data, a
netobject or bare cograph_network built from sequences, or a tna
model. A one-hot network built with "relative", "frequency" or
"co_occurrence" is clustered by unit, each actor's or session's windows
forming one sequence; a wtna network is refused (see data).
Covariates can be related to the clusters after the fit (see
covariates); they never change the assignments.
Every dissimilarity and method returns k groups, whether or not the
sequences fall into groups. The average silhouette width (Rousseeuw,
1987), which print() reports, compares each sequence's mean
dissimilarity to its own cluster with that to the nearest other cluster:
it runs from -1 to 1, values near 1 meaning well-separated clusters and
values near 0 overlapping ones. It describes one solution and is not a
test. Compare values of k, dissimilarities and methods with
cluster_choice(), check the classification with cluster_diagnostics(),
and build one network per cluster with build_network() (or
cluster_network() in one call) to see how the groups differ.
Usage
build_clusters(
data,
k,
dissimilarity = "hamming",
method = "pam",
na_syms = c("*", "%"),
weighted = FALSE,
lambda = 1,
seed = NULL,
q = 2L,
p = 0.1,
covariates = NULL,
estimator = c("auto", "firth", "multinom", "chisq"),
...
)
## S3 method for class 'net_clustering'
print(x, digits = 3L, ...)
## S3 method for class 'net_clustering'
summary(object, ...)
## S3 method for class 'net_clustering'
plot(
x,
type = c("silhouette", "mds", "heatmap", "predictors"),
combined = TRUE,
...
)
## S3 method for class 'tidy_covariates'
print(x, ...)
Arguments
data |
The sequences: a data frame or matrix with one row per
sequence and one column per position, holding state names; a
|
k |
The number of clusters, a whole number from 2 to one less than the number of sequences. Required. |
dissimilarity |
How two sequences are compared. |
method |
The clustering algorithm. |
na_syms |
The symbols read as missing values, besides |
weighted |
Whether to weight the Hamming distance by position, so
that a difference early in the sequences counts more than a late one
(see |
lambda |
The decay rate of the position weights when
|
seed |
An integer used as the random seed for clustering; the
session's own random stream is left as it was. Default |
q |
The length of the q-grams compared by |
p |
The Winkler prefix weight of |
covariates |
Variables describing each sequence (such as an
achievement level or a course), related to the clusters after they are
found; they never change the assignments. Give a column name, a
character vector of names, a one-sided formula such as
|
estimator |
How the relation between the covariates and the
clusters is estimated; it never affects the clustering. |
... |
Not used: an extra argument raises an error, here and in the
|
x |
For the |
digits |
For |
object |
For |
type |
For |
combined |
For |
Details
With the stringdist package installed, the distances are computed
by stringdist::stringdistmatrix() in C, many times faster than the base
R implementation for the edit distances. The base R implementation is
used when stringdist is absent, for weighted Hamming, and when the
data hold 62 or more states.
Value
A net_clustering object. print() shows the method,
dissimilarity and average silhouette width, then one row per cluster
with its size (count and percentage), mean within-cluster distance and,
for PAM, its medoid; after a covariate analysis it adds a line
naming the covariates. summary() prints the method, dissimilarity and
average silhouette width and a per-cluster table of sizes and mean
within-cluster distances, followed by the covariate analysis when there
is one, and returns a per-cluster table, or the covariate table after a
covariate analysis (see the methods' return value below). plot() draws
the silhouette widths, a map of the distances, the distance matrix or
the covariate effects. build_network() turns the clustering into one
network per cluster (a netobject_group), and
cluster_diagnostics() and session_ids() give the classification
quality and each sequence's cluster. The object's fields:
- data
The sequence positions that were clustered, one row per sequence: covariates and set-aside columns are removed, and a one-hot network gives one row per unit.
- k
Number of clusters.
- assignments
Integer vector of cluster memberships (1 to
k), one per sequence in row order.- silhouette
Average silhouette width over all sequences.
- sizes
Named integer vector of cluster sizes.
- method
Clustering method used.
- dissimilarity
Dissimilarity used.
- distance
The pairwise dissimilarities, a
distobject.- medoids
For PAM, the row numbers of the
kmedoid sequences; NULL for the hierarchical methods.- seed
Seed given (or NULL).
- weighted
Whether weighted Hamming was used.
- lambda
Decay rate used (0 when not weighted).
- covariates
The covariate analysis (a list; see
estimator), or NULL whencovariates = NULL.- network_method, build_args
For
netobjectinput, the source network's method and the arguments that read its data, so per-cluster networks are of the same type. NULL otherwise. For a one-hot network,build_argsholds only the settings that make its type inparams(such as a co-occurrence network'stype), or is NULL when it has none.- network_settings
For
netobjectinput, the source network'sthresholdandscalingwhen they are not the defaults and its estimator settings inparams, whichbuild_network(x, inherit = TRUE)uses; NULL when there are none.- metadata
For
netobjectinput, its per-sequence metadata, one row per clustered sequence, sosession_idscan name each sequence. For a data frame, the columns set aside as covariates (seedata). NULL otherwise, and for a one-hot network.- htna_partition
For HTNA input, the preserved node-to-actor partition used to restore HTNA children when networks are built.
For the print() methods: the input, invisibly. print() of a
tidy_covariates table prints a header naming the estimator, then the
table. For summary(): a data frame with one row per cluster and
columns cluster, size and mean_within_dist, returned visibly
after the printed summary. For a clustering fitted with covariates,
the printed summary adds the covariate profiles and the logit or test
tables, and a tidy_covariates data frame is returned invisibly
instead: one row per cluster and predictor (cluster, predictor,
OR, CI_low, CI_high, p, sig) for a logit, or one row per
covariate (variable, type, statistic, df, p, effect,
effect_kind, sig) for estimator = "chisq", with the per-cluster
table, fit statistics and profiles attached as attributes. For
plot(): a ggplot object, drawn and returned invisibly; with
type = "predictors" and combined = FALSE, a list of ggplot
objects, one per non-reference cluster and named by it, returned
invisibly without drawing.
References
Kaufman, L., & Rousseeuw, P. J. (1990). Finding Groups in Data: An Introduction to Cluster Analysis. Wiley.
Rousseeuw, P. J. (1987). Silhouettes: A graphical aid to the interpretation and validation of cluster analysis. Journal of Computational and Applied Mathematics, 20, 53–65. doi:10.1016/0377-0427(87)90125-7
Examples
seqs <- data.frame(V1 = c("A","B","C","A","B"), V2 = c("B","C","A","B","A"),
V3 = c("C","A","B","C","B"))
cl <- build_clusters(seqs, k = 2)
cl
seqs <- data.frame(
V1 = sample(LETTERS[1:3], 20, TRUE), V2 = sample(LETTERS[1:3], 20, TRUE),
V3 = sample(LETTERS[1:3], 20, TRUE), V4 = sample(LETTERS[1:3], 20, TRUE)
)
cl <- build_clusters(seqs, k = 2)
print(cl)
summary(cl)
Estimate a co-occurrence network analysis (CNA) model
Description
build_network(method = "co_occurrence"), or for short build_cna(),
estimates a co-occurrence network analysis (CNA) model: an undirected
network of states that occur in the same sequence. The edge between state
A and state B counts the pairs of positions in one sequence that hold A
and B, in either order (Saqr et al., 2025).
An edge says how often two states occur together, not which came first;
for order, use build_tna(). One-hot codes are counted in windows, as
build_wtna() does.
Usage
build_cna(
data,
start = FALSE,
end = FALSE,
actor = NULL,
action = NULL,
time = NULL,
session = NULL,
...,
order = NULL,
time_threshold = 900,
timezone = "UTC",
state_cols = NULL,
metadata_cols = NULL,
codes = NULL,
window_size = 3L,
mode = c("non-overlapping", "overlapping"),
type = c("frequency", "relative"),
group = NULL,
scaling = NULL,
threshold = 0,
labels = NULL,
params = list()
)
Arguments
data |
The sequences: a data frame with one row per sequence and one
column per position, an event log (one row per event, with |
start |
A start state put before every sequence, so the network
shows where sequences begin (an edge from it to each sequence's first
state). |
end |
An end state put in the cell after each sequence's last
observed state, so the network shows where sequences stop. It has no
outgoing edges and no self-loop, unlike |
actor |
The column naming who each row belongs to (a person, a
team). In an event log, each actor's events form a sequence, split
further by |
action |
The column holding each event's state; setting it declares
the data an event log. Column names give no role: |
time |
The timestamp column of an event log. Events are ordered by
it, and a gap longer than |
session |
The column identifying sessions in an event log; each
session is its own sequence, also without |
... |
Further arguments for |
order |
The column that orders events sharing a timestamp; without
it, those events keep their row order. Default |
time_threshold |
The longest gap, in seconds, between two events of
the same sequence in an event log; a longer gap starts a new sequence.
|
timezone |
The Olson time zone for timestamps without an offset
(passed to |
state_cols |
The columns of a wide table that are sequence
positions; every other column goes to the network's metadata. Declared
columns are positions even when they hold only 0 and 1. With nothing
declared, the frame must be one column or hold position columns named
as a numbered run (a shared prefix and a number, |
metadata_cols |
Columns to keep as the network's metadata
(covariates), never as positions; they cannot overlap |
codes |
The one-hot code columns (one per state, 1 when the state is
active); setting them declares one-hot data. Default |
window_size |
For one-hot data: how many consecutive rows form one
window. Default |
mode |
For one-hot data: |
type |
|
group |
A column to split the data by: one network per value,
returned as a |
scaling |
Rescaling applied to the weights after estimation, in the
order given: |
threshold |
Weights whose absolute value is below this are set to
zero. Default |
labels |
New display labels for the nodes, applied after estimation:
a two-column data frame ( |
params |
Settings for the estimator, as a named list. Transitions
are counted with tna's |
Value
A netobject (a netobject_group with group), as
build_network() returns it.
References
Saqr, M., López-Pernas, S., Törmänen, T., Kaliisa, R., Misiejuk, K., & Tikka, S. (2025). Transition network analysis: A novel framework for modeling, visualizing, and identifying the temporal patterns of learners and learning processes. In Proceedings of the 15th International Learning Analytics and Knowledge Conference (LAK25) (pp. 351–361). ACM. doi:10.1145/3706468.3706513
See Also
build_network() for every method; build_tna() for the order
of states.
Examples
build_network(trajectories, method = "co_occurrence")
build_cna(trajectories)
build_cna(trajectories, scaling = "max", threshold = 0.1)
Estimate a correlation network
Description
build_network(method = "cor"), or for short build_cor(), estimates a
correlation network of numeric variables. The edge between two variables
is their correlation (Epskamp & Fried, 2018).
A correlation edge is a marginal association: it can come from a shared
link with a third variable. To separate direct from indirect links, use
build_pcor() or build_glasso(). Check the stability of the edges with
bootstrap_network().
Usage
build_cor(
data,
actor = NULL,
level = NULL,
...,
cor_method = c("pearson", "spearman", "kendall"),
predictability = TRUE,
metadata_cols = NULL,
group = NULL,
scaling = NULL,
threshold = 0,
labels = NULL,
params = list()
)
Arguments
data |
The variables: a data frame with one row per observation and
one column per variable, or a square symmetric correlation or
covariance matrix, which needs the sample size in |
actor |
The id column naming whose observation each row is (a
person). With |
level |
Multilevel decomposition, with |
... |
Further arguments for |
cor_method |
|
predictability |
Whether to compute each node's predictability (the
R-squared of the node on its neighbours). It is stored on the network,
and |
metadata_cols |
Columns to keep as the network's metadata
(covariates), never read as variables. Default |
group |
A column to split the data by: one network per value,
returned as a |
scaling |
Rescaling applied to the weights after estimation, in the
order given: |
threshold |
Weights whose absolute value is below this are set to
zero. Default |
labels |
New display labels for the nodes, applied after estimation:
a two-column data frame ( |
params |
Settings for the estimator, as a named list, such as |
Value
A netobject (a netobject_group with group, a netobject_ml
with level = "both"), as build_network() returns it: print it for
an overview, read the edges with extract_edges(), and draw it with
cograph::splot().
References
Epskamp, S., & Fried, E. I. (2018). A tutorial on regularized partial correlation networks. Psychological Methods, 23(4), 617–634. doi:10.1037/met0000167
Saqr, M., Beck, E., & López-Pernas, S. (2024). Psychological networks: A modern approach to analysis of learning and complex learning processes. In M. Saqr & S. López-Pernas (Eds.), Learning Analytics Methods and Tutorials: A Practical Guide Using R. Springer. doi:10.1007/978-3-031-54464-4_19
See Also
build_network() for every method; build_pcor(),
build_glasso() and build_ising() for the other association
networks; bootstrap_network() and nct() for inference.
Examples
build_network(srl_strategies, method = "cor")
build_cor(srl_strategies)
build_cor(srl_strategies, cor_method = "spearman", threshold = 0.2)
Estimate a frequency transition network analysis (FTNA) model
Description
build_network(method = "frequency"), or for short build_ftna(),
estimates a frequency transition network analysis (FTNA) model from
sequences of states. The edge from state A to state B is the number of
times B comes right after A (Saqr et al., 2025).
Counts grow with the number and length of sequences, so they compare
within one network; for transition probabilities use build_tna(). A
matrix given as data must hold non-negative whole counts. Check how far
the counts move under resampling with bootstrap_network().
Usage
build_ftna(
data,
start = FALSE,
end = FALSE,
actor = NULL,
action = NULL,
time = NULL,
session = NULL,
...,
order = NULL,
time_threshold = 900,
timezone = "UTC",
state_cols = NULL,
metadata_cols = NULL,
codes = NULL,
window_size = 3L,
mode = c("non-overlapping", "overlapping"),
group = NULL,
scaling = NULL,
threshold = 0,
labels = NULL,
params = list()
)
Arguments
data |
The sequences: a data frame with one row per sequence and one
column per position, an event log (one row per event, with |
start |
A start state put before every sequence, so the network
shows where sequences begin (an edge from it to each sequence's first
state). |
end |
An end state put in the cell after each sequence's last
observed state, so the network shows where sequences stop. It has no
outgoing edges and no self-loop, unlike |
actor |
The column naming who each row belongs to (a person, a
team). In an event log, each actor's events form a sequence, split
further by |
action |
The column holding each event's state; setting it declares
the data an event log. Column names give no role: |
time |
The timestamp column of an event log. Events are ordered by
it, and a gap longer than |
session |
The column identifying sessions in an event log; each
session is its own sequence, also without |
... |
Further arguments for |
order |
The column that orders events sharing a timestamp; without
it, those events keep their row order. Default |
time_threshold |
The longest gap, in seconds, between two events of
the same sequence in an event log; a longer gap starts a new sequence.
|
timezone |
The Olson time zone for timestamps without an offset
(passed to |
state_cols |
The columns of a wide table that are sequence
positions; every other column goes to the network's metadata. Declared
columns are positions even when they hold only 0 and 1. With nothing
declared, the frame must be one column or hold position columns named
as a numbered run (a shared prefix and a number, |
metadata_cols |
Columns to keep as the network's metadata
(covariates), never as positions; they cannot overlap |
codes |
The one-hot code columns (one per state, 1 when the state is
active); setting them declares one-hot data. Default |
window_size |
For one-hot data: how many consecutive rows form one
window. Default |
mode |
For one-hot data: |
group |
A column to split the data by: one network per value,
returned as a |
scaling |
Rescaling applied to the weights after estimation, in the
order given: |
threshold |
Weights whose absolute value is below this are set to
zero. Default |
labels |
New display labels for the nodes, applied after estimation:
a two-column data frame ( |
params |
Settings for the estimator, as a named list. Transitions
are counted with tna's |
Value
A netobject (a netobject_group with group), as
build_network() returns it: print it for an overview, read the edges
with extract_edges() and the counts with extract_transition_matrix(),
and draw it with cograph::splot().
References
Saqr, M., López-Pernas, S., Törmänen, T., Kaliisa, R., Misiejuk, K., & Tikka, S. (2025). Transition network analysis: A novel framework for modeling, visualizing, and identifying the temporal patterns of learners and learning processes. In Proceedings of the 15th International Learning Analytics and Knowledge Conference (LAK25) (pp. 351–361). ACM. doi:10.1145/3706468.3706513
See Also
build_network() for every method; build_tna(),
build_atna() and build_cna() for the other transition networks.
Examples
build_network(trajectories, method = "frequency")
build_ftna(trajectories)
build_ftna(group_regulation_long, actor = "Actor", action = "Action",
time = "Time", group = "Achiever")
Estimate a gap transition network analysis model
Description
build_network(method = "gap"), or for short build_gap(), estimates a
gap transition network analysis model, which links each state to the
states up to max_gap + 1 positions later, each pair weighted by one
over its distance, as tna::build_model(type = "gap") does.
The weights are raw weighted counts; add scaling = "normalize" for row
probabilities.
Usage
build_gap(
data,
start = FALSE,
end = FALSE,
actor = NULL,
action = NULL,
time = NULL,
session = NULL,
order = NULL,
time_threshold = 900,
timezone = "UTC",
state_cols = NULL,
metadata_cols = NULL,
max_gap = 1L,
group = NULL,
scaling = NULL,
threshold = 0,
labels = NULL,
params = list(),
...
)
Arguments
data |
The sequences: a data frame with one row per sequence and one
column per position, or an event log (one row per event, with |
start |
A start state put before every sequence, so the network
shows where sequences begin (an edge from it to each sequence's first
state). |
end |
An end state put in the cell after each sequence's last
observed state, so the network shows where sequences stop. It has no
outgoing edges and no self-loop, unlike |
actor |
The column naming who each row belongs to (a person, a
team). In an event log, each actor's events form a sequence, split
further by |
action |
The column holding each event's state; setting it declares
the data an event log. Column names give no role: |
time |
The timestamp column of an event log. Events are ordered by
it, and a gap longer than |
session |
The column identifying sessions in an event log; each
session is its own sequence, also without |
order |
The column that orders events sharing a timestamp; without
it, those events keep their row order. Default |
time_threshold |
The longest gap, in seconds, between two events of
the same sequence in an event log; a longer gap starts a new sequence.
|
timezone |
The Olson time zone for timestamps without an offset
(passed to |
state_cols |
The columns of a wide table that are sequence
positions; every other column goes to the network's metadata. Declared
columns are positions even when they hold only 0 and 1. With nothing
declared, the frame must be one column or hold position columns named
as a numbered run (a shared prefix and a number, |
metadata_cols |
Columns to keep as the network's metadata
(covariates), never as positions; they cannot overlap |
max_gap |
How many states may lie between the two states of a pair,
a whole number of at least 0. Default |
group |
A column to split the data by: one network per value,
returned as a |
scaling |
Rescaling applied to the weights after estimation, in the
order given: |
threshold |
Weights whose absolute value is below this are set to
zero. Default |
labels |
New display labels for the nodes, applied after estimation:
a two-column data frame ( |
params |
Settings for the estimator, as a named list, as for
|
... |
Further arguments for |
Value
A netobject (a netobject_group with group), as
build_network() returns it.
References
Tikka, S., López-Pernas, S., & Saqr, M. (2025). tna: An R package for transition network analysis. Applied Psychological Measurement. doi:10.1177/01466216251348840
See Also
build_network() for every method; build_ngram() and
build_reverse() for the other tna model types.
Examples
build_network(trajectories, method = "gap", max_gap = 2)
build_gap(trajectories, max_gap = 2)
Estimate person-specific networks with GIMME
Description
build_gimme() estimates a directed network for each person from
intensive longitudinal data with GIMME (group iterative multiple model
estimation; Gates & Molenaar, 2012), in the unified structural equation
model (uSEM): each variable at time t is regressed on the variables
at t - 1 (temporal, lagged paths) and on the other variables at
t (contemporaneous paths). The search runs in two stages:
-
Group-level paths: directed paths added for everyone because they would improve the model for a large share of the people (more than the share
groupcutoff, by default0.75, of the people whose models converged). -
Individual-level paths: further paths specific to each person, added after the group paths until that person's model fits well (see
n_excellent).
It takes one long data frame with a person-ID column, not a directory of CSV files.
The temporal and contemporaneous count matrices say how many people have each path, which shows how common a path is in the sample, not how strong it is; the coefficients are estimated per person. Group paths are shared by construction, while individual paths are what the search adds for one person's series: before reading them, check each person's number of time points and fit statistics, which the result carries.
Usage
build_gimme(
data,
vars,
id,
time = NULL,
ar = TRUE,
standardize = FALSE,
groupcutoff = 0.75,
subcutoff = 0.5,
paths = NULL,
exogenous = NULL,
hybrid = FALSE,
rmsea_cutoff = 0.05,
srmr_cutoff = 0.05,
nnfi_cutoff = 0.95,
cfi_cutoff = 0.95,
n_excellent = 2L,
seed = NULL
)
## S3 method for class 'net_gimme'
coefs(x, ...)
Arguments
data |
A data frame in long format: one row per person and time point, with the person-ID column, the variables and, optionally, a time or beep column. |
vars |
The names of the variables to model, at least two, all
columns of |
id |
The name of the person-ID column. The data must hold at least two people; a person with fewer than three time points is left out of the analysis without a warning. |
time |
The name of the time or order column. When given, the rows
are sorted by |
ar |
Whether each variable's autoregressive path (itself at lag 1)
is fixed into every model. Default |
standardize |
Whether the variables are standardised within each
person before estimation. Default |
groupcutoff |
A path is added at the group level when it is
significant for more than this share of the people whose models
converged, a number in (0, 1]. No group path is added when half or fewer
of the models converge. Default |
subcutoff |
Not used. It is accepted for compatibility with gimme, where it sets the subgrouping cutoff; subgrouping is not implemented, so the value is not passed on. Default |
paths |
Paths, in lavaan syntax, to fix into every model, such as
|
exogenous |
The variables treated as exogenous (predictors only),
all among |
hybrid |
Whether the search also considers residual covariances
between the variables at the same time point. Default |
rmsea_cutoff |
The RMSEA at or below which a person's fit counts as
excellent. Default |
srmr_cutoff |
The SRMR at or below which a person's fit counts as
excellent. Default |
nnfi_cutoff |
The NNFI (TLI) at or above which a person's fit counts
as excellent. Default |
cfi_cutoff |
The CFI at or above which a person's fit counts as
excellent. Default |
n_excellent |
How many of the four fit indices must be excellent for
a person's individual search to stop, a whole number from 1 to 4.
Default |
seed |
An integer that makes the estimation reproducible; the
session's own random stream is left as it was. Default |
x |
For the |
... |
For the |
Details
Estimation is delegated to idiographic::fit_gimme(), the clean-room home
of the temporal idiographic estimators, whose search reproduces the
upstream gimme package (>= 10.0) exactly (verified at tolerance 0 on
path counts and per-person coefficient matrices in idiographic's own
parity suite). The models are fitted with lavaan, which also gives
the modification indices the search uses; build_gimme() raises an error
when lavaan is not installed. The settings build_gimme() does not
expose (such as the multiple-comparison corrections and alpha) keep
idiographic::fit_gimme()'s defaults.
Value
The net_gimme object, also a cograph_network, that idiographic::fit_gimme() returns; its print(), summary() and
plot() methods are idiographic's, not Nestimate's. print()
shows the group-level paths, the number of individual paths and the
share of people with each path; summary() returns a data frame with
one row per network layer (temporal, contemporaneous) and its size,
density and weights; plot() draws the network. idiographic::edges()
gives one row per path with its level (group or individual), and
idiographic::coefs() one row per person and path with its
coefficient. The object is a superset of the pre-0.9.0
in-package field contract: every field below is present, alongside
idiographic's additions (contemp_cov, contemp_cov_avg,
contemp_is_cov). Its fields:
temporalp x p matrix of temporal (lagged) path counts: entry
[i, j]is the number of people with the path j(t-1) -> i(t), group and individual paths alike.contemporaneousp x p matrix of contemporaneous path counts: entry
[i, j]is the number of people with the path j(t) -> i(t).temporal_avg,contemporaneous_avgp x p group-average coefficient matrices.
coefsList of per-person p x 2p coefficient matrices (rows the endogenous variables, columns the lagged and then the contemporaneous variables).
psiList of per-person residual covariance matrices.
fitData frame of per-person fit indices (
file, the person, then chisq, df, pvalue, rmsea, srmr, nnfi, cfi, bic, aic, logl and status).path_countsp x 2p matrix: how many people have each path.
pathsList of per-person character vectors of lavaan path syntax.
group_pathsCharacter vector of the group-level paths found.
individual_pathsList of per-person character vectors of the individual-level paths (beyond the group paths).
syntaxList of per-person full lavaan syntax strings.
labelsCharacter vector of variable names.
n_subjectsNumber of people.
n_obsInteger vector of the lagged time points per person (its rows minus one).
configList of the settings used, including the corrections and cutoffs that are not arguments here.
The object also carries idiographic's network fields (nodes,
edges, directed, data, meta,
node_groups, and a weights entry that is NULL) for
rendering with cograph.
Results changed in 0.9.0
Before 0.9.0 the search ran in an in-package implementation that was
not upstream-gimme-exact. Delegating to
idiographic::fit_gimme() changed which paths the search selects on the
same data – individual-level paths in particular – so numeric results
are not comparable with Nestimate <= 0.8.5. The returned object also
gained fields (see Value); nothing was removed.
Methods
-
coefs()on abuild_gimme()result returns idiographic's coefficient table, one row per person and path. Nestimate's owncoefs()generic masks idiographic's when both packages are attached; this method makes either one give the same table.
References
Gates, K. M., & Molenaar, P. C. M. (2012). Group search algorithm recovers effective connectivity maps for individuals in homogeneous and heterogeneous samples. NeuroImage, 63(1), 310–319. doi:10.1016/j.neuroimage.2012.06.026
See Also
Examples
# Create simple panel data (3 subjects, 4 variables, 30 time points).
set.seed(42)
n_sub <- 3; n_t <- 30; vars <- paste0("V", 1:4)
rows <- lapply(seq_len(n_sub), function(i) {
d <- as.data.frame(matrix(rnorm(n_t * 4), ncol = 4))
names(d) <- vars; d$id <- i; d
})
panel <- do.call(rbind, rows)
res <- build_gimme(panel, vars = vars, id = "id")
print(res)
Estimate an EBIC graphical lasso network
Description
build_network(method = "glasso"), or for short build_glasso(),
estimates an EBIC graphical lasso network, a Gaussian graphical model,
from numeric variables. The edge between two variables is their partial
correlation given all the others, shrunk by the graphical lasso, with the
penalty chosen by EBIC (Friedman et al., 2008; Foygel & Drton, 2010).
The penalty is chosen along a path of nlambda values; an L1 penalty
sets small partial correlations to exactly zero. An absent edge means the
penalty removed it at the selected lambda, not that the two variables are
shown to be independent. Check the stability of the edges and
centralities with boot_glasso().
Usage
build_glasso(
data,
actor = NULL,
level = NULL,
...,
gamma = 0.5,
nlambda = 100L,
cor_method = c("pearson", "spearman", "kendall"),
predictability = TRUE,
metadata_cols = NULL,
group = NULL,
scaling = NULL,
threshold = 0,
labels = NULL,
params = list()
)
Arguments
data |
The variables: a data frame with one row per observation and
one column per variable, or a square symmetric correlation or
covariance matrix, which needs the sample size in |
actor |
The id column naming whose observation each row is (a
person). With |
level |
Multilevel decomposition, with |
... |
Further arguments for |
gamma |
The EBIC hyperparameter: larger values give sparser
networks. Default |
nlambda |
The number of penalties tried. Default |
cor_method |
|
predictability |
Whether to compute each node's predictability (the
R-squared of the node on its neighbours). It is stored on the network,
and |
metadata_cols |
Columns to keep as the network's metadata
(covariates), never read as variables. Default |
group |
A column to split the data by: one network per value,
returned as a |
scaling |
Rescaling applied to the weights after estimation, in the
order given: |
threshold |
Weights whose absolute value is below this are set to
zero. Default |
labels |
New display labels for the nodes, applied after estimation:
a two-column data frame ( |
params |
Settings for the estimator, as a named list:
|
Value
A netobject (a netobject_group with group, a netobject_ml
with level = "both"), as build_network() returns it.
References
Friedman, J., Hastie, T., & Tibshirani, R. (2008). Sparse inverse covariance estimation with the graphical lasso. Biostatistics, 9(3), 432–441. doi:10.1093/biostatistics/kxm045
Foygel, R., & Drton, M. (2010). Extended Bayesian information criteria for Gaussian graphical models. Advances in Neural Information Processing Systems, 23, 604–612.
See Also
build_network() for every method; build_pcor() for the
unregularised network; boot_glasso() and nct() for inference.
Examples
build_network(srl_strategies, method = "glasso")
build_glasso(srl_strategies)
build_glasso(srl_strategies, gamma = 0.75)
Build a higher-order network from sequences
Description
build_hon() builds a higher-order network from sequences with the
BuildHON algorithm (Xu, Wickramarathne & Chawla, 2016) or its faster
variant BuildHON+ (Saebi et al., 2020), and returns a net_hon. A node
is a state together with as much of its preceding history as changes
where the sequence goes next: "B" is a first-order node, and "A -> B"
is state B reached from A, kept as a node of its own when the
distribution of the next state after A then B differs enough from the one
after B alone (see Details), or when it begins a longer history that is
kept, such as "A -> B -> C". It reads sequences in a wide data frame
or character matrix, a list of state vectors, or a netobject,
cograph_network or tna built from sequences.
An edge weight is the probability of moving from the source node to the
target node. A higher-order node marks a dependence on earlier states that
a first-order network, with one node per state, averages away. Whether a
history is extended is decided by a rule, not a test: the Kullback-Leibler
divergence between the longer and the shorter history's next-state
distributions must exceed a threshold that grows with the order and
shrinks with how often the longer history was observed, so the same
divergence passes more easily for a history observed more often, and
nodes resting on a few observations are noisy (raise min_freq to set
them aside). To test whether the sequences
need memory beyond the first order, use markov_order_test();
build_mogen() selects an order by likelihood, and pathways() lists the
higher-order paths found here.
Usage
build_hon(
data,
max_order = 5L,
min_freq = 1L,
collapse_repeats = FALSE,
method = "hon+"
)
## S3 method for class 'net_hon'
print(x, ...)
## S3 method for class 'net_hon'
summary(object, ...)
Arguments
data |
The sequences. A data frame or character matrix has one row
per sequence and one column per position; a data frame of several
columns must hold only position columns named as a numbered run ( |
max_order |
The highest order a node may reach, that is, how many
states of history it carries. Default |
min_freq |
The minimum count for a transition to be used.
Transitions observed fewer than |
collapse_repeats |
Whether to collapse each run of a repeated state
into one state before counting (after splitting at missing values).
Default |
method |
The algorithm. |
x |
For the |
... |
Ignored by the |
object |
For the |
Details
Node names: a first-order node is the state itself, "A". A
second-order node for "came from A, now at B" is "A -> B"; a
third-order one is "A -> B -> C", and so on.
Algorithm:
Count the transitions from every history of up to
max_orderstates (subsequences of up tomax_order + 1states); BuildHON+ counts the longer histories only when they are needed.Turn the counts into next-state distributions, setting counts below
min_freqto zero.For each first-order source, extend the history one state at a time and keep the longer history when the Kullback-Leibler divergence (base 2) of its distribution from the currently kept one exceeds
order / log2(1 + n), whereorderis the new order andnthe number of transitions counted from the longer history (after setting counts belowmin_freqto zero).Build the network from the kept histories, rewiring edges so the higher-order nodes are connected to each other.
The implementation follows the reference Python code of the two papers (pyHON and pyHON+).
Value
A net_hon (class c("net_hon", "cograph_network")). Print it
for the number of nodes, edges and sequences and the orders reached;
summary() prints the same with the first-order states and the number
of nodes of each order, and returns the network's edge table (integer
from/to node indices and weight). extract_edges() gives the
weight of each ordered pair of nodes by node name (pairs with zero
weight are included at its default threshold = 0, and self-loops only
with include_self = TRUE), pathways() the higher-order paths,
build_honem() an embedding of the nodes and
build_simplicial(type = "pathway") a simplicial complex; it draws with
cograph::splot(). The print() method returns its input invisibly.
The fields:
- weights, matrix
The weighted adjacency matrix (rows are sources, columns targets) under two names:
weightsis thecograph_networkfield,matrixthe higher-order name kept for compatibility. Rows and columns carry the node names in arrow notation (e.g."A -> B").- ho_edges
The higher-order edge table, one row per edge:
path(the full state sequence, e.g."A -> B -> C"),from(the source node, its history),to(the next state),count(how often the transition was observed),probability(the transition probability), andfrom_orderandto_order(the orders of the source and target nodes).- edges
The
cograph_networkedge table: one row per non-zero cell ofweights, with integerfrom/toindices intonodesand a numericweight. It is not the arrow-notation table, which isho_edges.- nodes
A data frame with columns
id,labelandname, one row per node;labelandnamehold the node names in arrow notation.- n_nodes
The number of nodes.
- n_edges
The number of rows of
ho_edges.- first_order_states
The distinct states of the sequences analysed (after splitting at missing values, collapsing repeats and dropping short sequences), sorted.
- max_order_requested
The
max_orderused.- max_order_observed
The highest order reached.
- min_freq
The
min_freqused.- n_trajectories
The number of sequences analysed, after splitting at missing values and dropping short ones.
- directed
Always
TRUE.- meta
The
cograph_networkmetadata list (source,layout, andtna$method = "hon").- node_groups
Always
NULL.
References
Xu, J., Wickramarathne, T. L., & Chawla, N. V. (2016). Representing higher-order dependencies in networks. Science Advances, 2(5), e1600028.
Saebi, M., Xu, J., Kaplan, L. M., Ribeiro, B., & Chawla, N. V. (2020). Efficient modeling of higher-order dependencies in networks: from algorithm to application for anomaly detection. EPJ Data Science, 9(1), 15.
Examples
seqs <- list(c("A","B","C","D"), c("A","B","C","A"), c("B","C","D","A"))
hon <- build_hon(seqs, max_order = 2)
# From list of trajectories
trajs <- list(
c("A", "B", "C", "D", "A"),
c("A", "B", "D", "C", "A"),
c("A", "B", "C", "D", "A")
)
hon <- build_hon(trajs, max_order = 3, min_freq = 1)
print(hon)
summary(hon)
# From data.frame (rows = trajectories)
df <- data.frame(T1 = c("A", "A"), T2 = c("B", "B"),
T3 = c("C", "D"), T4 = c("D", "C"))
hon <- build_hon(df, max_order = 2)
Embed the nodes of a higher-order network with HONEM
Description
build_honem() places the nodes of a higher-order network (HON) in a
low-dimensional space, after the HONEM approach of Saebi et al. (2020):
nodes whose multi-step transition profiles are alike (where they lead in
one, two or more steps) get nearby coordinates. It reads a net_hon from
build_hon(), whose higher-order nodes (such as "A -> B") are embedded
beside the first-order ones, or any square weighted adjacency matrix. The
coordinates come from a decayed multi-step proximity matrix (see
Details).
The coordinates have no units and the sign of each dimension is
arbitrary; what carries meaning is how close nodes lie to each other.
The variance explained says how much of the proximity matrix the dim
kept dimensions reproduce; a plot of two of them shows less than that.
Usage
build_honem(hon, dim = 32L, max_power = 10L)
## S3 method for class 'net_honem'
print(x, ...)
## S3 method for class 'net_honem'
summary(object, ...)
## S3 method for class 'net_honem'
plot(x, dims = c(1L, 2L), ...)
Arguments
hon |
The network to embed: a |
dim |
The number of embedding dimensions. Default |
max_power |
|
x |
For the |
... |
For the |
object |
For the |
dims |
For the |
Details
No random walks or skip-gram are used: the coordinates come from the
truncated singular value decomposition of the proximity matrix. With
D the row-normalised transition matrix over all HON nodes (rows
without outgoing edges stay zero), the proximity matrix is
S = Z^{-1} \sum_{k=0}^{L} e^{-k} D^{k+1} with
Z = \sum_{k=0}^{L} e^{-k} and L = max_power, where
D^{k+1} is a matrix power. Each node's embedding is its row of
U_d \sqrt{\Sigma_d}, from the first d = dim singular
vectors and values of S. explained_variance is the share of the
sum of squared singular values held by the first d; S is not
centred, so this is not a principal-component variance.
How this differs from the paper. Saebi et al. write the same
sum, but there D^v is a v-th-order neighbourhood matrix
over first-order nodes (the superscript is an order, not a power),
filled from the HON edge weights of order-v dependencies, with L
the highest order present, rule extraction changed to keep every lower
order, and one embedding per first-order node. The paper gives no
formula for D^v, and its worked example (Supplementary Table S.1)
is internally inconsistent; no reference code is public. This function
therefore does not claim to reproduce the paper's embeddings.
Value
A net_honem object. print() shows the number of nodes, the
dimensions, max_power and the variance explained; summary() prints
the leading singular values and the range of the coordinates, and
returns one row per node; plot() draws the nodes on two dimensions.
The object's fields:
- embeddings
Numeric matrix (nodes x
dim) of coordinates, with the node names as row names and columnsdim_1,dim_2, ...- nodes
Character vector of node names.
- singular_values
The
dimleading singular values.- explained_variance
Share of the squared singular values held by the kept dimensions.
- dim
Embedding dimension used.
- max_power
L, the upper limit ofk; the highest matrix power used ismax_power + 1.- n_nodes
Number of nodes embedded.
The print() and plot() methods return the input invisibly.
summary() returns a data frame with one row per node: node (the node
name), then dim1, dim2, ... with the coordinates; the summary text is
printed as a side effect.
References
Saebi, M., Ciampaglia, G. L., Kaplan, L. M., & Chawla, N. V. (2020). HONEM: Learning Embedding for Higher Order Networks. Big Data, 8(4), 255-269.
Examples
seqs <- list(c("A","B","C","D"), c("A","B","C","A"), c("B","C","D","A"))
hem <- build_honem(build_hon(seqs, max_order = 2), dim = 2)
trajs <- list(c("A","B","C","D"), c("A","B","D","C"),
c("B","C","D","A"), c("C","D","A","B"))
hon <- build_hon(trajs, max_order = 2)
emb <- build_honem(hon, dim = 4)
print(emb)
plot(emb)
Detect over- and under-represented paths with HYPA
Description
build_hypa() tests which paths in a set of sequences occur more or less
often than expected, with HYPA (LaRock et al., 2020). For an order k it
builds the order-k De Bruijn graph, whose nodes are runs of k states
and whose edges are paths of k + 1 states, and compares each path's
count with a hypergeometric null model that keeps every node's observed
in- and out-strength. Paths that are rarer than the null model allows are
labelled under-represented, paths that are more common over-represented,
and the rest normal. Unobserved paths that the observed transitions make
possible are tested too, so a path that never occurs can be
under-represented. Several orders can be tested in one call.
A path is over-represented when its last state follows its k-state
context more often than the null model predicts from the strengths of the
De Bruijn nodes alone (at order 2, from the first-order transitions).
Each path is tested on its own at alpha, so with many possible paths
some are flagged by chance: p_adjust corrects for that, and with small
counts the upper-tail test rejects more often than alpha (see
p_adjust). Whether the sequences need a higher order overall is a
separate question, tested by markov_order_test(); build_mogen()
selects an order and build_hon() builds a network of variable order.
Usage
build_hypa(
data,
order = 2L,
alpha = 0.05,
min_count = 5L,
p_adjust = "none",
k = NULL
)
## S3 method for class 'net_hypa'
print(x, ...)
## S3 method for class 'net_hypa'
summary(
object,
n = 10L,
type = c("all", "over", "under"),
order_by = c("sig", "freq", "frequency", "ratio", "path"),
...
)
Arguments
data |
The sequences: a wide data frame (one row per trajectory,
position columns only, named as a numbered run), a character matrix
with the same layout, a list of character vectors, a |
order |
The order or orders of the De Bruijn graph, whole numbers of
at least 1 without duplicates. Default |
alpha |
The significance threshold for the labels, a number in
(0, 0.5). Default |
min_count |
The smallest count a path needs to be labelled, a whole
number of at least 1. Default |
p_adjust |
The correction of the p-values for multiple testing: any
of stats::p.adjust.methods, such as |
k |
The former name of |
x |
For the |
... |
For the |
object |
For the |
n |
For the |
type |
For the |
order_by |
For the |
Details
Internal missing states split a trajectory, so no path spans a gap, and
pieces shorter than two states are dropped. State labels must not
contain the control characters "\x01" or "\x02", which are used
internally as separators; such labels raise an error of class
nestimate_hypa_bad_label.
The possible paths of order k link each node with an observed outgoing
path to every node with an observed incoming path that continues it (its
last k - 1 states are the other's first) through an observed
first-order transition; at order 1 they are the observed transitions.
The propensity matrix of the null model is fitted
on them by continuous iterative proportional fitting; when the fit does
not reach its tolerance, a warning of class nestimate_hypa_no_converge
is raised. The original Python implementation rounds the propensities
inside every sweep, so its expected counts can differ from these by a
few thousandths.
As in the original implementation, when an order has only one possible
path, that path's upper-tail p-value is 0, so it is labelled
over-represented once it is observed min_count times, even when its
count equals the expected one.
Value
A net_hypa object (class c("net_hypa", "cograph_network")).
print() reports the orders, the number of paths tested and how many
are over- and under-represented (per order when there are several);
summary() prints and returns the strongest anomalies; pathways()
gives the anomalous paths as pathway strings for
cograph::plot_simplicial(). The object's fields:
- scores
A data frame with one row per possible path of each order: every observed path and every unobserved one the observed transitions permit (
observed = 0). Within each order the over-represented paths come first (by decreasing ratio), then the under-represented (by increasing ratio), then the rest. Columns:path, the full state sequence ("A -> B -> C");from, the context (the conditioning states);to, the next state;observed;expected, the count under the null model, whose propensity matrix keeps the observed in- and out-strength of every De Bruijn node (at order 2 this equals the first-order Markov expectationn(a b \cdot) n(\cdot b c) / n(\cdot b \cdot)), from the continuous fit;ratio, observed / expected;p_under, the hypergeometric lower-tail probabilityP(X <= observed), whose pool sizes are the propensities rounded to whole numbers, as the hypergeometric distribution requires, so its mean can differ fromexpectedby up to about0.5 / mformobserved paths of that order; andp_value, the same value under its older name;p_over, the strict upper tailP(X > observed) = 1 - p_under, so thatp_over <= alphais the paper's HYPA score of at least1 - alpha;p_adjusted_underandp_adjusted_over, the same afterp_adjust;anomaly("over","under"or"normal"); andorder.- ho_edges
The same table as
scores, under the name the other higher-order builders use.- over, under
The rows of
scoreslabelled over- or under-represented.- adjacency
The weighted adjacency matrix (path counts) of the lowest-order De Bruijn graph.
- weights
The cograph weight matrix of the lowest-order graph.
- xi
The fitted propensity matrix of the lowest-order graph.
- edges
The cograph edge data frame of the lowest-order graph.
- by_order
A list with the results of each order built, named by order.
- order
The orders built, ascending.
- k
The same as
order, kept for backward compatibility.- alpha
The significance threshold used.
- p_adjust
The correction used.
- n_anomalous, n_over, n_under
The number of anomalous, over- and under-represented paths, over all orders.
- n_edges
The number of possible paths tested, over all orders.
- nodes
A data frame (
id,label,name) of the nodes of the lowest-order De Bruijn graph;labelandnameare the node'skstates joined by the internal separator"\x01", as are the dimnames ofadjacency,weightsandxi.- directed
Always
TRUE.- meta
The cograph meta list of the lowest-order graph.
- node_groups
Always
NULL.
print() returns its input invisibly. summary() prints the
settings, the anomaly counts and the top n paths of each direction,
and returns invisibly a data frame of those paths, one row per path:
order (the De Bruijn order the path was tested at), path,
observed, expected, ratio, p_tail (the raw tail probability of
its direction, p_over for over-represented paths and p_under for
under-represented ones) and direction ("over" or "under"). When
nothing is anomalous it is a zero-row data frame with the same columns
except order.
References
LaRock, T., Nanumyan, V., Scholtes, I., Casiraghi, G., Eliassi-Rad, T., & Schweitzer, F. (2020). HYPA: Efficient Detection of Path Anomalies in Time Series Data on Networks. SDM 2020, 460-468.
Examples
seqs <- list(c("A","B","C"), c("B","C","A"), c("A","C","B"), c("A","B","C"))
hyp <- build_hypa(seqs, order = 2)
trajs <- list(c("A","B","C"), c("A","B","C"), c("A","B","C"),
c("A","B","D"), c("C","B","D"), c("C","B","A"))
h <- build_hypa(trajs, order = 2)
print(h)
Build a hypergraph from a network's cliques
Description
build_hypergraph() turns a network into a hypergraph by promoting its
cliques to hyperedges: every set of 3 to max_size nodes that are all
tied to each other becomes a hyperedge, kept with probability p, and
the pairwise edges can be kept as hyperedges of size 2. It takes a
netobject, a bare cograph_network, a simplicial_complex or an
adjacency or weight matrix, and returns a net_hypergraph, the input of hypergraph_measures() and the other hypergraph verbs.
A hyperedge built this way records that every pair of its nodes is tied
in the thresholded network; a pairwise network cannot show whether those
nodes also act together as a group. When group memberships are observed
directly, bipartite_groups() builds the hypergraph from them instead.
Each clique also contributes its smaller cliques: with max_size = 4, a
4-clique gives one hyperedge of size 4 and four of size 3.
Usage
build_hypergraph(
net,
p = 1,
method = c("clique", "vr", "rips"),
include_pairwise = TRUE,
max_size = 3L,
threshold = 0,
seed = NULL
)
## S3 method for class 'net_hypergraph'
print(x, ...)
## S3 method for class 'net_hypergraph'
summary(object, ...)
Arguments
net |
The network: a |
p |
The probability that each clique of 3 or more nodes becomes a
hyperedge, a number in |
method |
How hyperedges are found. |
include_pairwise |
Whether the pairwise edges of the thresholded
network become hyperedges of size 2. |
max_size |
The largest hyperedge size, at least 2. Default |
threshold |
The cut-off that turns weights into ties: an edge is
kept when its absolute weight is non-zero and at least |
seed |
An integer that makes the sampling reproducible when
|
x |
For the |
... |
Not used. |
object |
For the |
Details
The construction follows Burgio, Matamalas, Gomez and Arenas (2020) on
cooperation in networks and hypergraphs. The cliques are found with
build_simplicial(), and each clique of 3 or more nodes then goes
through an independent Bernoulli(p) trial that decides whether it
becomes a hyperedge. The pairwise edges are not sampled: with
include_pairwise = TRUE all of them are kept, so the hypergraph holds
the pairwise structure and the sampled higher-order interactions
together.
At the limits:
-
p = 0withinclude_pairwise = TRUEgives the thresholded pairwise network as a hypergraph of size-2 edges. -
p = 1withinclude_pairwise = FALSEgives only the hyperedges of size 3 or more, every clique of the network's clique complex up tomax_size.
Value
A net_hypergraph object. print() shows the numbers of nodes
and hyperedges, the size distribution and the settings, and returns
its input invisibly. summary() prints the counts with the mean and
largest hyperedge size, and returns a data frame with one row per node:
node and degree, the number of hyperedges that contain it. The
object holds:
hyperedgesA list of integer vectors, one per hyperedge, each the sorted indices of the nodes it spans; pairwise edges, when kept, come first.
incidenceAn integer matrix of nodes by hyperedges, 1 where a node belongs to a hyperedge and 0 elsewhere. Its row names are the node names and its column names
h1,h2, ...nodesThe node names.
n_nodes,n_hyperedgesThe numbers of nodes and hyperedges.
size_distributionA named integer vector with the number of hyperedges of each size, named
size_2,size_3, ...paramsThe settings used:
method,p,include_pairwise,max_size,thresholdandseed.
References
Burgio, G., Matamalas, J. T., Gomez, S., & Arenas, A. (2020). Evolution of cooperation in the presence of higher-order interactions: from networks to hypergraphs. Entropy 22(7), 744. doi:10.3390/e22070744
See Also
build_simplicial() (the clique enumeration),
bipartite_groups(), build_network().
Examples
set.seed(1)
n <- 8
adj <- matrix(stats::rbinom(n * n, 1, 0.5), n, n)
diag(adj) <- 0
adj <- (adj + t(adj)) > 0
rownames(adj) <- colnames(adj) <- LETTERS[seq_len(n)]
hg <- build_hypergraph(adj, p = 1, max_size = 3L)
print(hg)
summary(hg)
Estimate an Ising model
Description
build_network(method = "ising"), or for short build_ising(),
estimates an Ising model of binary variables. The edge between two
variables is their interaction, fitted by L1-penalised logistic
regression of each variable on the others, with the penalty chosen by
EBIC, and the two estimates of each edge combined into one undirected
weight (van Borkulo et al., 2014). It needs the glmnet package.
An edge is a conditional association between two variables given all the others; an absent edge means the penalty removed it.
Usage
build_ising(
data,
actor = NULL,
...,
gamma = 0.25,
nlambda = 100L,
rule = c("AND", "OR"),
metadata_cols = NULL,
group = NULL,
scaling = NULL,
threshold = 0,
labels = NULL,
params = list()
)
Arguments
data |
The binary variables: a data frame with one row per
observation and one column per variable, holding only 0 and 1.
Non-numeric columns and a column named |
actor |
An id column naming whose observation each row is; it is
set aside, not modelled. Default |
... |
Further arguments for |
gamma |
The EBIC hyperparameter. Default |
nlambda |
The number of penalties tried. Default |
rule |
|
metadata_cols |
Columns to keep as the network's metadata
(covariates), never read as variables. Default |
group |
A column to split the data by: one network per value,
returned as a |
scaling |
Rescaling applied to the weights after estimation, in the
order given: |
threshold |
Weights whose absolute value is below this are set to
zero. Default |
labels |
New display labels for the nodes, applied after estimation:
a two-column data frame ( |
params |
Settings for the estimator, as a named list. The network
stores them, so the resampling verbs re-estimate with the same settings.
Default |
Value
A netobject (a netobject_group with group), as
build_network() returns it.
References
van Borkulo, C. D., Borsboom, D., Epskamp, S., Blanken, T. F., Boschloo, L., Schoevers, R. A., & Waldorp, L. J. (2014). A new method for constructing networks from binary data. Scientific Reports, 4, 5918. doi:10.1038/srep05918
See Also
build_network() for every method; build_mgm() for mixed
continuous and categorical variables.
Examples
if (requireNamespace("glmnet", quietly = TRUE)) {
set.seed(1)
binary <- data.frame(matrix(rbinom(200, 1, 0.5), ncol = 5))
build_network(binary, method = "ising")
build_ising(binary, rule = "OR")
}
Estimate a latency network analysis model
Description
build_network(method = "latency"), or for short build_latency(),
estimates a latency network analysis model from a message log. The edge
from sender A to sender B is the average weight of A's replies to B,
each reply weighted by its speed: 1 for an immediate reply, falling
linearly to floor at cap (Templeton et al., 2022).
Its edges are the replies of build_reverse(): within each sequence (an
actor's events, split by session or time_threshold), each event
points from its sender, the responder, to the sender of the event before
it. A reply that takes t seconds weighs
1 - (1 - f) \min(t / c, 1), with
f the floor and c the cap in seconds, and the weights of
a pair are averaged, or summed with aggregate = "sum". A sender who posts twice in
a row is a self-loop on the diagonal, weighted by the same rule. Shifting
every time by a constant leaves the weights unchanged, and so does a
change of time unit when the cap is a percentile. extract_edges() adds
each edge's number of replies (n_replies) and their median latency in
seconds (median_latency). start, end and
params = list(weighted = TRUE) raise an error of class
nestimate_bad_input. bootstrap_network() resamples latency networks
by their sequences and judges stability on the speed score; the other
resampling verbs, such as permutation(), raise an error of class
nestimate_latency_resampling on one.
In build_network() the four settings are named latency_floor,
latency_cap, latency_aggregate and latency_scope.
Usage
build_latency(
data,
action,
time,
actor = NULL,
session = NULL,
order = NULL,
time_threshold = 900,
timezone = "UTC",
floor = 0.5,
cap = 0.95,
aggregate = c("mean", "sum"),
scope = c("global", "actor", "session", "responder"),
group = NULL,
scaling = NULL,
threshold = 0,
labels = NULL,
...
)
Arguments
data |
A message log: one row per message, |
action |
The column holding each message's sender. |
time |
The timestamp column. Events are ordered by it, and a gap
longer than |
actor |
The column naming who each row belongs to (a person, a
team). In an event log, each actor's events form a sequence, split
further by |
session |
The column identifying sessions in an event log; each
session is its own sequence, also without |
order |
The column that orders events sharing a timestamp; without
it, those events keep their row order. Default |
time_threshold |
The longest gap, in seconds, between two events of
the same sequence in an event log; a longer gap starts a new sequence.
|
timezone |
The Olson time zone for timestamps without an offset
(passed to |
floor |
The weight of a reply that takes |
cap |
The time at which a reply's weight reaches |
aggregate |
How the replies of a pair of senders make one weight:
|
scope |
With a percentile |
group |
A column to split the data by: one network per value,
returned as a |
scaling |
Rescaling applied to the weights after estimation, in the
order given: |
threshold |
Weights whose absolute value is below this are set to
zero. Default |
labels |
New display labels for the nodes, applied after estimation:
a two-column data frame ( |
... |
Further arguments for |
Value
A netobject (a netobject_group with group), as
build_network() returns it. Beside the weights it keeps initial,
n_replies and median_latency (matrices laid out as the weights),
latency_cap_seconds (the resolved global cap), latency_unit_caps
(the per-unit caps of a non-global scope) and latency_time, the
event times in seconds.
References
Templeton, E. M., Chang, L. J., Reynolds, E. A., Cone LeBeaumont, M. D., & Wheatley, T. (2022). Fast response times signal social connection in conversation. Proceedings of the National Academy of Sciences, 119(4), e2116915119. doi:10.1073/pnas.2116915119
See Also
build_network() for every method; build_reverse() for the
unweighted replies.
Examples
build_network(group_regulation_long, method = "latency", actor = "Actor",
action = "Action", time = "Time")
build_latency(group_regulation_long, action = "Action", time = "Time",
actor = "Actor")
Build an MCML model of cluster and within-cluster transitions
Description
build_mcml() builds a Multi-Cluster Multi-Level (MCML) model from
transitions: it recodes every state to its cluster and counts the
transitions that occur, which gives the Markov chain over clusters (the
macro network) and one network per cluster of the transitions among its
own states. It reads sequences (one row per sequence), event logs (with
action), edge lists (with from and to), tna models and
netobjects that carry their data, and it re-partitions an existing
mcml (see combine and expand). A weight matrix has no transitions to
count, so it is passed to cluster_summary(), which aggregates the
weights instead.
With the defaults (type = "tna", method = "sum"), a macro edge is the
probability that the
next state lies in cluster j given that the current one lies in cluster i;
its diagonal is the probability of staying in a cluster, whether in the
same state or a different one. Both levels depend on the partition, which
is the analyst's: compare a few partitions with combine and expand
rather than reading one. The weights are point estimates;
as_tna()
turns the levels into networks that carry their sequences, so
bootstrap_network() can show how far each edge moves under resampling.
Usage
build_mcml(
x,
clusters = NULL,
method = c("sum", "mean", "median", "max", "min", "density", "geomean"),
type = c("tna", "frequency", "cooccurrence", "raw"),
directed = TRUE,
compute_within = TRUE,
actor = NULL,
action = NULL,
time = NULL,
order = NULL,
session = NULL,
time_threshold = 900,
exclude = NULL,
trim = NULL,
end = FALSE,
end_by = NULL,
labels = NULL,
combine = NULL,
expand = NULL,
from = NULL,
to = NULL,
weight = NULL,
cols = NULL
)
## S3 method for class 'mcml_layer'
print(x, ...)
## S3 method for class 'mcml'
print(x, ...)
## S3 method for class 'mcml'
summary(object, ...)
Arguments
x |
The data. Accepted forms:
A data frame that declares no role and is not a numbered run of
positions, or whose columns hold only 0 and 1, raises an error of class
|
clusters |
The cluster of each state. Accepted forms:
Every state must belong to exactly one cluster, the |
method |
How the transitions between (or within) two clusters are
combined into one weight, with |
type |
How the aggregated counts are turned into weights:
|
directed |
Whether transitions are directed. Default |
compute_within |
Whether to build the within-cluster networks.
Default |
actor, action, time, order, session, time_threshold |
For an event log:
the columns and the session gap (in seconds, default |
exclude |
States to drop before anything is counted, such as a
technical marker. In an event log the matching events are removed
before sequences are formed, so a dropped state never takes a position;
in wide sequences the matching cells become missing. Default |
trim |
How much of each sequence to keep. |
end |
A terminal state put in the cell after each sequence's last
observed state. |
end_by |
Columns grouping the terminal marker at a coarser unit than
the sequence: only the sequence holding each group's last event is
marked. For example,
|
labels |
New display labels for the states of the within-cluster
networks, applied after estimation: a two-column data frame
( |
combine, expand |
Change the partition. |
from, to, weight |
The columns of an edge list: its source, its target
and an optional non-negative weight (each transition counts 1 without
it). Names give no role: a frame is read as an edge list only when
|
cols |
For a wide data frame: the columns holding the positions,
needed when the frame is anything but a numbered run ( |
... |
For the |
object |
For |
Value
An mcml object with the layout described under
cluster_summary(). Print it for the type, the method, the node and
cluster counts, the clusters,
the number of transitions between and within clusters and the macro
weights; printing one layer (an mcml_layer) shows its node and edge
counts, weight range, weight matrix, initial probabilities and the size
of the data it carries. summary() returns a data frame with one row
per cluster, with
columns cluster, size, within_total (the total absolute weight of
the within-cluster network, each observation once as on the macro
diagonal: an undirected edge of a weight matrix once, an undirected
transition count as its two halves; NA when it was not built),
between_out
and between_in (the absolute macro weight leaving and entering the
cluster, diagonal excluded); for an undirected macro network, between_out is
the total incident weight and between_in is NA.
as_tna() turns
the levels into a netobject_group, as_htna() rebuilds the
node-level network with its clusters, macro_network() opens chosen
clusters into their states, and sequence_plot() draws the sequences
by cluster. The print() methods return their input invisibly.
On the sequence and edge-list routes, the object differs from the matrix route's in these fields:
- edges
A data frame with one row per observed node-level transition and columns
from,to,weight,cluster_from,cluster_toandtype("within"or"between").- macro
Its
initsare the shares of the clusters among the first-column states (missing cells left out), or the normalised column sums for an edge list; itsdataholds the sequences recoded to cluster labels, or onefrom/torow per transition for an edge list.- clusters
Each layer counts only the transitions between states of its own cluster. Its
initsare the shares of its states among the first-column states that belong to it (normalised column sums for an edge list), and itsdatathe sequences with the states of other clusters set missing (for an edge list, its within-cluster transitions).- meta
sourceis"transitions",typerecords thetypeused, anddirectedwhether the stored weights are directed (FALSEfortype = "cooccurrence").
Input passed to cluster_summary() gives its result: source
"matrix" in meta, and no edge table.
See Also
cluster_summary for matrix-based aggregation,
as_tna to promote the layers to netobjects,
macro_network for the cluster-level network with one
cluster expanded
Examples
# Edge list with clusters: its columns are declared
edges <- data.frame(
source = c("A", "A", "B", "C", "C", "D"),
target = c("B", "C", "A", "D", "D", "A"),
count = c(1, 2, 1, 3, 1, 2)
)
clusters <- list(G1 = c("A", "B"), G2 = c("C", "D"))
build_mcml(edges, clusters, from = "source", to = "target", weight = "count")
# Sequence data with clusters
seqs <- data.frame(
T1 = c("A", "C", "B"),
T2 = c("B", "D", "A"),
T3 = c("C", "C", "D"),
T4 = c("D", "A", "C")
)
cs <- build_mcml(seqs, clusters, type = "raw")
cs
summary(cs)
# Change the partition while building ...
three <- build_mcml(seqs, list(G1 = "A", G2 = "B", G3 = c("C", "D")))
build_mcml(seqs, list(G1 = "A", G2 = "B", G3 = c("C", "D")),
combine = c("G1", "G2"))
# ... or re-partition an existing mcml: the model is re-estimated
build_mcml(three, combine = c("G1", "G2")) # G1 + G2 as one cluster
build_mcml(three, combine = list(AB = c("G1", "G2"))) # named merge
build_mcml(three, expand = "G3") # C and D as clusters
Build an MCML model of a psychometric network
Description
build_mcml_pc() collapses a psychometric network whose nodes are assigned
to clusters into a cluster-level (macro) network and one within-cluster
network per cluster, and returns an mcml_pc object. It is the counterpart
of build_mcml() for undirected association networks: it reads a
netobject estimated with cor, pcor or glasso, or a numeric data
frame of observations, from which it estimates the node-level network
first. Experimental: the API and the aggregation formulas may
change between releases.
Partial correlations do not aggregate by arithmetic. The submatrix of a
partial-correlation matrix is not the partial-correlation network of
that subsystem, because the conditioning set changes, and averaging entries
across blocks is descriptive only. The aggregations (see aggregation)
therefore differ in status:
- Score paths, re-estimated (
"scaled","composite","mean","median","loadings") Each observation gets one score per cluster, formed from the cluster's member items (see
weighting), and the estimator inmethodis re-fitted on these scores, so the macro network is a genuine correlation, partial-correlation or EBICglasso network among clusters. Needs raw data."average"(descriptive)The macro edge between clusters A and B is the mean of the signed node-level weights between members of A and members of B; the macro diagonal is the mean within-block off-diagonal weight. Needs only the weight matrix, so it works on a netobject without data. Signed averaging can cancel opposite-sign edges: read it as a net average association, not a connection strength.
"escoufier"(descriptive, multivariate)The macro edge is Escoufier's RV coefficient between the member blocks, a matrix correlation in
[0, 1]computed from the block covariance structure. No scores are formed and nothing is re-estimated, so nothing is lost to averaging; signs are not represented. Needs raw data."cancor"(descriptive, multivariate)The macro edge is the first canonical correlation between the member blocks: the strongest linear relationship any weighting of A's items can have with any weighting of B's items, an upper bound on what the score paths can recover. Needs raw data.
Every aggregation inherits the cluster assignment. Before reading the macro
network, check the item table with item_loadings(): an item more strongly
connected to another cluster than to its own is flagged as misfit and
named in a warning. A flagged item means every aggregation carries a
doubtful membership, so fix the assignment rather than ignore the flag.
How far the composite weights move under case resampling is checked with
loading_stability(). The macro network of a score path carries its
scores as data, so bootstrap_network() (edge-weight intervals) and,
with at least three clusters, vertex_bootstrap() (network-level
intervals) work on it directly, as in
bootstrap_network(macro_network(fit)), and vertex_compare() (also with
at least three clusters) compares the macro networks of two fits;
macro_network() extracts it.
Usage
build_mcml_pc(
x,
clusters,
aggregation = c("scaled", "composite", "mean", "median", "loadings", "average",
"escoufier", "cancor"),
method = c("pcor", "glasso", "cor"),
within = c("reestimate", "subnetwork"),
weighting = c("equal", "strength", "eigen", "closeness", "betweenness",
"expected_influence", "specificity", "pca", "factor", "item_total"),
cor_method = c("pearson", "spearman", "polychoric"),
signed = TRUE,
id_col = NULL,
fa_method = c("ml", "paf", "minres", "cfa"),
...
)
## S3 method for class 'mcml_pc'
print(x, digits = 3, ...)
## S3 method for class 'mcml_pc'
summary(object, ...)
## S3 method for class 'mcml_pc'
plot(x, digits = 2, ...)
Arguments
x |
The network or the data. A |
clusters |
The cluster membership, in one of three forms: a named list of node-label vectors (the names are the cluster labels), a data frame whose first column holds the node names and second column the cluster labels (read by position, column names are not used), or a vector of cluster labels named by node. Every node must belong to exactly one cluster, every member must be a node, and at least two clusters are needed; anything else raises an error. |
aggregation |
How the clusters are collapsed into the macro network.
Default
The descriptive ones relate the blocks without forming scores:
|
method |
The network estimator for the node-level network of a data
frame, the macro network of the score paths and the re-estimated
within-cluster networks: |
within |
How the within-cluster networks are formed: |
weighting |
How the items are weighted inside their cluster score on
the score paths; on
Network-based and data-based weightings answer different questions, and
comparing them is informative: when they diverge, the network's view of
the cluster differs from its latent-variable view. The schemes whose
weights cannot be negative ( |
cor_method |
The correlation used when estimating from raw data:
|
signed |
Whether reverse-keyed items are flipped in the cluster
scores (see Details). Default |
id_col |
Identifier columns to drop from data-frame input before the
analysis. Default |
fa_method |
The extraction method for
On well-behaved unidimensional clusters the four agree closely; a divergence points to a cluster prone to Heywood cases or not unidimensional. |
... |
Further arguments passed to the |
digits |
For the |
object |
For the |
Details
Item diagnostics. Every item's mean absolute connection to the
other members of every cluster is computed from the node-level
network. item_loadings() reports, per item, its own-cluster loading
(signed by the eigenvector orientation; a sign-carrying weighting is
recorded in the sign column instead), its composite weight, its strongest cross-cluster loading and the
cluster that loading points to, and a misfit flag set when the cross-cluster
loading exceeds the own-cluster loading. A singleton cluster has no
within-cluster connections, so its item is never flagged.
Reverse-keyed items. With signed = TRUE (default), the item
signs come from the leading eigenvector of the within-cluster block of the
node-level network, oriented so most items are positive. An item with a
negative sign enters its cluster score with sign -1, so a reverse-keyed
item reinforces its cluster score instead of cancelling it. Flips are
reported in the sign column of item_loadings() and, on the score
paths, in a warning. On the score paths a sign-carrying weighting sets the
signs from its own values instead (see weighting).
Missing data. Cluster scores are row-wise weighted means over the
observed members, with the weights renormalised per row; a row with
no observed member is NA and the estimator drops it with a message.
Node-level estimation applies the estimators' own complete-case handling,
and "escoufier" and "cancor" use the rows complete on every item.
Ordinal items. cor_method = "polychoric" (needs the
lavaan package) estimates the node-level and within-cluster networks
from polychoric correlations, which suits Likert items. Cluster scores are
continuous, so the macro network is always re-estimated from their Pearson
correlations.
Within-cluster networks follow within. "reestimate" re-fits
the estimator on the member columns alone, giving the conditional
structure of the subsystem; "subnetwork" slices the node-level weight
matrix and is descriptive (for pcor and glasso it keeps the
conditioning on items outside the cluster). Input without raw data always
uses "subnetwork". A singleton cluster gets no within-cluster network
(NULL).
All constituent networks are undirected (meta$directed = FALSE), so
renderers that detect directedness, such as cograph::plot_mcml(), draw
them without arrowheads.
Value
An mcml_pc object. print() shows the aggregation, estimator,
cluster sizes, the misfit and flipped-item counts (when there are any)
and the macro weights;
summary() returns one row per macro edge; plot() draws the macro
weights as a heatmap. item_loadings() gives the item table,
composites() the cluster scores of a score path, macro_network() the
macro network, as_networks() the macro and within-cluster networks as
a netobject_group, loading_stability() the stability of the
composite weights, and cograph::plot_mcml() draws the two-layer
network. The object's fields:
- macro
The cluster-level netobject (k x k, undirected).
- clusters
Named list of within-cluster netobjects (
NULLfor a singleton cluster).- cluster_members
Named list of each cluster's node labels.
- loadings
The item table that
item_loadings()returns, one row per node.- node_network
The node-level netobject the aggregation was based on, kept for the diagnostics and
loading_stability().- data
The raw data as a data frame when available, else
NULL.- composites
The cluster scores of a score path, else
NULL.- meta
List:
aggregation(the name as the caller spelled it),method,within,weighting,weighting_spec(the scheme itself, a custom vector or function included),fa_method,fa_args,scale,cor_method,signed,n_nodes,n_clusters,cluster_sizes,n_misfit,n_flipped,directed = FALSE,source = "pc"andexperimental = TRUE.methodandweightingareNAon the descriptive paths, which re-estimate no macro network, andfa_method/fa_argsare set only forweighting = "factor".
For the methods: print() returns x invisibly; summary()
returns a data frame with one row per macro edge (the upper triangle)
and columns from, to and weight; plot() returns a ggplot.
Methods
-
plot()draws the macro (cluster-level) weights as a heatmap in the package's diverging palette, with each weight printed in its tile.cograph::plot_mcml()draws both layers as undirected networks.
References
Escoufier, Y. (1973). Le traitement des variables vectorielles. Biometrics, 29(4), 751-760.
Hotelling, H. (1936). Relations between two sets of variates. Biometrika, 28(3/4), 321-377.
Robinaugh, D. J., Millner, A. J., & McNally, R. J. (2016). Identifying highly influential nodes in the complicated grief network. Journal of Abnormal Psychology, 125(6), 747-757.
Christensen, A. P., & Golino, H. (2021). On the equivalency of factor and network loadings. Behavior Research Methods, 53, 1563-1580.
Epskamp, S., & Fried, E. I. (2018). A tutorial on regularized partial correlation networks. Psychological Methods, 23(4), 617-634.
See Also
build_mcml() for transition networks; loading_stability() for the stability of the composite weights; bootstrap_network() and vertex_bootstrap() for the uncertainty of the macro network.
Examples
set.seed(1)
n <- 200
sigma <- matrix(0.15, 6, 6)
sigma[1:3, 1:3] <- 0.5
sigma[4:6, 4:6] <- 0.5
diag(sigma) <- 1
z <- matrix(rnorm(n * 6), n, 6) %*% chol(sigma)
df <- as.data.frame(z)
names(df) <- c("a1", "a2", "a3", "b1", "b2", "b3")
clusters <- list(A = c("a1", "a2", "a3"), B = c("b1", "b2", "b3"))
fit <- build_mcml_pc(df, clusters, aggregation = "composite",
method = "cor")
fit # macro (cluster-level) weights
summary(fit) # one row per macro edge
plot(fit) # heatmap of the same weights
Estimate a mixed graphical model (MGM)
Description
build_network(method = "mgm"), or for short build_mgm(), estimates a
mixed graphical model (MGM) of continuous and categorical variables. The
edge between two variables is the strength of their interaction, fitted
by penalised node-wise regression with the penalty chosen by EBIC
(Haslbeck & Waldorp, 2020).
Factor and character columns are categorical, and an integer column with
at most 10 values is categorical with a warning. Missing continuous
values are filled with the observed column mean and missing categorical
values with the modal level; this keeps the rows and is psychnets'
documented na_method = "pairwise" policy, not pairwise deletion.
Usage
build_mgm(
data,
actor = NULL,
level = NULL,
lambdaGam = 0.25,
ruleReg = c("AND", "OR"),
metadata_cols = NULL,
group = NULL,
scaling = NULL,
threshold = 0,
labels = NULL,
params = list(),
...
)
Arguments
data |
The variables: a data frame with one row per observation and one column per variable, continuous or categorical. |
actor |
The id column naming whose observation each row is (a
person). With |
level |
With |
lambdaGam |
The EBIC hyperparameter. Default |
ruleReg |
|
metadata_cols |
Columns to keep as the network's metadata
(covariates), never read as variables. Default |
group |
A column to split the data by: one network per value,
returned as a |
scaling |
Rescaling applied to the weights after estimation, in the
order given: |
threshold |
Weights whose absolute value is below this are set to
zero (default |
labels |
New display labels for the nodes, applied after estimation:
a two-column data frame ( |
params |
Settings for the estimator, as a named list. The network
stores them. Default |
... |
Further arguments for |
Value
A netobject (a netobject_group with group), as
build_network() returns it.
References
Haslbeck, J. M. B., & Waldorp, L. J. (2020). mgm: Estimating time-varying mixed graphical models in high-dimensional data. Journal of Statistical Software, 93(8), 1–46. doi:10.18637/jss.v093.i08
See Also
build_network() for every method; build_ising() for binary
variables, build_glasso() for continuous ones.
Examples
if (requireNamespace("glmnet", quietly = TRUE)) {
set.seed(1)
mixed <- data.frame(x = rnorm(100), y = rnorm(100),
g = factor(sample(c("a", "b"), 100, TRUE)))
build_network(mixed, method = "mgm")
build_mgm(mixed)
}
Estimate multilevel vector autoregression networks
Description
build_mlvar() fits a multilevel vector autoregression to intensive
longitudinal panel data (ESM or EMA: many people, each measured on many
occasions) and returns its three networks. The temporal network is
directed and holds the fixed-effect lagged regression coefficients: the
weight in row i, column j is the coefficient of variable i at an
earlier occasion on variable j now, so each edge runs from the earlier
variable to the one it predicts.
The contemporaneous network is undirected: the partial correlations of
the within-person residuals at the same occasion. The between-subjects
network is undirected too: the partial correlations of the person means.
Each variable is regressed, in a mixed model, on every variable
lag occasions earlier and on the other variables' person means; the
temporal and contemporaneous effects are fixed and only the intercepts are
random.
The temporal and contemporaneous edges describe within-person relations
averaged over people; the between-subjects edges describe how people who
differ in one variable on average differ in another (Epskamp et al.,
2018). Only random intercepts are estimated, so the networks do not show
how people differ in their dynamics. A temporal edge is a lagged
predictive association, and a contemporaneous edge has no temporal order.
coefs() gives each temporal coefficient with its standard error,
p-value and confidence interval; check them before interpreting any
single temporal edge.
Usage
build_mlvar(
data,
vars,
id,
day = NULL,
beep = NULL,
lag = 1L,
standardize = FALSE
)
## S3 method for class 'net_mlvar'
print(x, ...)
## S3 method for class 'net_mlvar'
summary(object, ...)
## S3 method for class 'net_mlvar'
plot(x, layer = NULL, ...)
Arguments
data |
The panel data: a data frame with one row per measurement
occasion. A column named in |
vars |
The columns to model, at least two. |
id |
The column identifying the person each row belongs to. |
day |
The column identifying the day (or session) of each row. When
given, lagged pairs are formed only within the same day. Default |
beep |
The column numbering the measurement occasions. When |
lag |
How many occasions back the predictors of the temporal network
are, a whole number of at least 1: |
standardize |
Whether to grand-mean centre each variable and divide
it by its pooled SD before the panel is augmented, as
|
x |
For the |
... |
For the |
object |
For the |
layer |
For the |
Details
Estimation is done by idiographic::fit_mlvar(), called with
estimator = "lmer", temporal = "fixed" and contemporaneous = "fixed". It follows mlVAR's lmer path:
Drop rows with NA in id/day/beep and, with
standardize = TRUE, grand-mean standardise each variable.Expand the per-(id, day) beep grid and right-join the original values, giving the augmented panel (
augData).Add within-person lagged predictors (
L1_*) and person-mean predictors (PM_*).For each outcome variable fit
lmer(y ~ within + between-except-own-PM + (1 | id))withREML = FALSE. Collect the fixed-effect temporal matrixB, the between-effect matrixGamma, the random-intercept SDs (mu_SD) and the lmer residual SDs.Contemporaneous network:
cor2pcor(D %*% cov2cor(cor(resid)) %*% D).Between-subjects network:
cor2pcor(pseudoinverse(forcePositive(D (I - Gamma)))).
The result agrees with mlVAR::mlVAR() to machine precision (largest
difference below 1e-10) on 25 real ESM datasets from openesm and 20
simulated configurations, and exactly with the implementation Nestimate
carried before 0.9.0 on all layers, coefficients and observation counts,
across settings of lag, standardize, day and beep.
The temporal weight matrix has predictors in rows and outcomes in columns,
the transpose of mlVAR's Beta and the same matrix as
mlVAR::getNet(, "temporal"). A Nestimate network reads its weight matrix
from row to column, so the edges of the temporal network (its edge list
and extract_edges()) run from the predictor at t - lag to the outcome
at t. Nestimate 1.0.9 and earlier did not transpose it, so every
temporal edge pointed from the outcome to its predictor.
When the data carry no between-person variance (a random-intercept SD of zero), the between-subjects network cannot be estimated. Since 0.9.0 idiographic then raises a warning and the zero matrix is returned by convention; before 0.9.0 the zero matrix was returned silently.
Value
A net_mlvar object (class c("net_mlvar", "netobject_group")):
a named list of three networks, with the model-level results stored as
attributes. print() gives the number of subjects, observations and
variables, the lag, and how many temporal edges are significant;
coefs() returns the temporal coefficients, one row per outcome and
predictor; summary() prints the three weight matrices and the
significant temporal edges and returns the same table as coefs(),
visibly, so at the console the matrices are followed by the table.
idiographic registers its own print() and summary() methods
for net_mlvar; Nestimate loads it first and registers its methods
after, so these two are the ones that run. Each
network is a netobject (class c("netobject", "cograph_network"))
built from its weight matrix, without data; the Dispatch limitation
section lists the verbs that do not work on it. The parts:
temporalDirected network of the
d x dmatrix of fixed-effect lagged coefficients: the weight in rowi, columnjis the effect of variableiatt - lagon variablejatt, so edges run from predictor to outcome. Method"mlvar_temporal".contemporaneousUndirected
d x dnetwork of the partial correlations of the within-person lmer residuals. Method"mlvar_contemporaneous".betweenUndirected
d x dnetwork of the partial correlations of the person means, derived fromD (I - Gamma). Method"mlvar_between".- coefficient table (attribute
coefs) The data frame
coefs()returns: one row per(outcome, predictor)pair, with columnsoutcome,predictor,beta,se,t,p,ci_lower,ci_upperandsignificant.- attribute
n_obs The number of rows of the augmented panel after rows with missing values are removed.
- attribute
n_subjects The number of subjects remaining.
- attribute
lag The lag used.
- attribute
standardize Whether the variables were standardised before augmentation.
The print() method returns its input invisibly.
Dispatch limitation
plot() draws the three networks side by side, or one with layer,
with cograph::splot() when cograph is installed and in base
graphics otherwise; each constituent can also be drawn on its own
(cograph::splot() on the temporal network). The constituents are
wrappers around their weight matrices and carry no
data, so the verbs that resample or reread the data,
bootstrap_network(), network_reliability() and
centrality_stability(), raise an error on the fit and on each
constituent, and certainty() refuses them as not transition networks.
net_centrality() and summary() read the weights and work on each
constituent. coefs() gives the model output.
Methods
-
summary.net_mlvar()prints the three weight matrices and the significant temporal edges, then returns the coefficient table ofcoefs().
References
Epskamp, S., Waldorp, L. J., Mõttus, R., & Borsboom, D. (2018). The Gaussian graphical model in cross-sectional and time-series data. Multivariate Behavioral Research, 53(4), 453–480. doi:10.1080/00273171.2018.1454823
See Also
Examples
# A three-variable ESM panel: 20 people x 20 beeps. `tired` is driven by
# `happy` one beep earlier, so the temporal network should recover it.
if (requireNamespace("lme4", quietly = TRUE)) {
set.seed(1)
n_beep <- 20
ar1 <- function(n, phi) as.numeric(stats::filter(stats::rnorm(n), phi,
method = "recursive"))
panel <- do.call(rbind, lapply(seq_len(20), function(i) {
happy <- ar1(n_beep, 0.4)
data.frame(
id = i,
beep = seq_len(n_beep),
happy = happy + stats::rnorm(1),
calm = ar1(n_beep, 0.3) + stats::rnorm(1),
tired = 0.5 * c(0, happy[-n_beep]) + stats::rnorm(n_beep) +
stats::rnorm(1)
)
}))
fit <- build_mlvar(panel, vars = c("happy", "calm", "tired"),
id = "id", beep = "beep")
fit
coefs(fit)
summary(fit)
}
Fit a mixed Markov model
Description
build_mmm() fits a mixture of first-order Markov chains to a set of
sequences by expectation-maximisation: it looks for k subgroups whose
members move between states in different ways, each with its own
transition matrix and initial-state distribution. Every sequence gets a
posterior probability of belonging to each subgroup and is assigned to the
most probable one. Covariates can shape the mixing proportions during
estimation or be related to the subgroups afterwards (see
covariate_effect).
EM finds a local maximum, so the fit is started n_starts times (one
start from k-means on the transition counts, the rest random), each is
screened with a short EM run, the most promising are continued for up to
max_iter iterations, and the one with the highest log-likelihood is
kept. print() reports whether it converged within
max_iter; a fit that did not is not a result. The information criteria
(BIC, AIC, ICL) compare fits with different k – compare_mmm() fits a
range of them – while average posterior probability (AvePP), entropy and
classification error describe how cleanly the sequences separate within
one fit. None of them picks k alone: also check that the subgroups'
transition matrices differ in ways that can be interpreted, and that
each subgroup holds enough sequences to estimate its matrix.
Usage
build_mmm(
data,
k = 2L,
n_starts = 50L,
max_iter = 200L,
tol = 1e-06,
smooth = 0.01,
seed = NULL,
covariates = NULL,
covariate_effect = c("em", "posthoc"),
estimator = c("auto", "firth", "multinom", "chisq")
)
## S3 method for class 'net_mmm'
print(x, digits = 3L, ...)
## S3 method for class 'net_mmm'
summary(object, ...)
## S3 method for class 'net_mmm'
plot(x, type = c("posterior", "covariates"), combined = TRUE, ...)
## S3 method for class 'net_mmm_clustering'
print(x, digits = 3L, ...)
## S3 method for class 'net_mmm_clustering'
plot(
x,
type = c("posterior", "covariates", "predictors"),
combined = TRUE,
...
)
Arguments
data |
The sequences: a data frame with one row per sequence and one
column per position, a |
k |
The number of subgroups (mixture components), a whole number of
at least 2. Default |
n_starts |
How many starting configurations to try, a positive whole
number. More starts make it likelier that the best local maximum is
found. Default |
max_iter |
The most EM iterations a start may run, a positive whole
number. Default |
tol |
The convergence tolerance: EM stops when the log-likelihood
changes by less than this between iterations (with |
smooth |
A pseudo-count added to every transition count before the
matrices are estimated, so a transition unseen in a subgroup gets a small
probability instead of zero. A finite non-negative number; default
|
seed |
An integer that makes the random starts reproducible.
Default |
covariates |
Variables describing each sequence (such as a course or
a grade), given as a column name, a character vector of names, a
one-sided formula or a data frame, as in |
covariate_effect |
How |
estimator |
How the after-fit multinomial logit is estimated; it never
affects the EM. |
x |
For the |
digits |
For the |
... |
For the |
object |
For the |
type |
For the |
combined |
For the |
Value
A net_mmm object. print() shows the fit statistics,
classification quality and subgroup sizes; summary() adds each
subgroup's transition matrix and returns one row per subgroup (mixing
proportion, sequences assigned, mean posterior, AvePP); plot() draws
the posterior probabilities or the covariate effects;
build_network() turns the fit into one network per subgroup (a
netobject_group); cluster_diagnostics() and session_ids() give the
classification and each sequence's subgroup. The object's fields:
- data
The full N-row sequence frame used for estimation.
- models
List of
netobjects, one per component. Each component carries the rows assigned to that component in its$dataslot, while its transition matrix is the EM-estimated component transition matrix.- k
Number of components.
- mixing
Numeric vector of mixing proportions.
- posterior
N x k matrix of posterior probabilities.
- assignments
Integer vector of hard assignments (1..k).
- quality
List:
avepp(per-class),avepp_overall,entropy,relative_entropy,classification_error,class_entropy.- log_likelihood, BIC, AIC, ICL
Model fit statistics.
- n_params
Number of free parameters behind BIC/AIC/ICL. With
covariate_effect = "em"it grows by(k - 1) * pforpcovariate columns.- iterations, converged
EM iterations used by the retained fit and whether it met
tol.- states
Character vector of state names.
- n_sequences
Number of sequences actually fitted (rows with missing covariates are dropped under
covariate_effect = "em").- covariates
The post-hoc covariate analysis (list), or NULL when
covariates = NULL.- network_method, build_args, htna_partition
Provenance kept from
netobject/ HTNA input so per-cluster networks are of the same type; NULL otherwise.- network_settings
For
netobjectinput, the network'sthresholdandscalingwhen they are not the defaults and its estimator settings inparams, whichbuild_network(x, inherit = TRUE)uses; NULL when there are none.- metadata
The
netobject's per-sequence metadata, one row per fitted sequence in the row order ofposterior, sosession_idscan name each sequence; NULL for other input.
The print() methods return their input invisibly. For a model
fitted with covariates, summary() also prints the covariate profiles
and effects and returns, invisibly, a tidy_covariates data frame of
the effects (one row per subgroup other than the reference and per
predictor term, so a factor gives one row per non-reference level; one
row per covariate test with estimator = "chisq"), with the
per-subgroup table as its cluster_stats attribute. The plot()
methods print the plot and return the ggplot invisibly; with
type = "covariates" and combined = FALSE they return, invisibly and
without printing, a list of ggplots named by subgroup.
Initial states
Each sequence's initial state is the value in its first position column,
read as it is: the function does not look ahead to the first observed
state, and it does not convert missing-value symbols as build_clusters()
does. The states are the distinct non-missing values of all position
columns, so a placeholder such as "*" or "%" for an empty cell becomes
a state, and a sequence starting with it starts in that state. Recode such
placeholders to NA first: a missing first position gives the sequence
no initial state, which leaves its subgroup to the transitions alone. Or
trim leading empty cells so every first position holds an observed state.
A one-hot network is different: its units are windows of codes, not positions, so its initial state is the one code active in the first window, and none when that window holds several codes or none.
Methods
print() of a net_mmm shows a header with the numbers of sequences,
subgroups and states, the log-likelihood and the information criteria; a
quality line with the overall AvePP, the normalised entropy (0 when every
sequence is classified with certainty, 1 when all posteriors are equal)
and the classification error (the expected share of sequences
misclassified when each is assigned to its most likely subgroup, the mean
of one minus the largest posterior; Vermunt & Magidson, 2005); a line when the EM did not converge;
and one row per subgroup with its size, mixing proportion and AvePP. For a
model fitted with covariates, a last line names them, says whether they
entered the EM (integrated) or were related post hoc, and gives their
number. The layout follows print() of a net_clustering from
build_clusters(), so dissimilarity-based and model-based clusterings read
alike.
build_network() on a fit, and cluster_network() with
cluster_by = "mmm", return a netobject_group whose "clustering"
attribute is a net_mmm_clustering: the fit without its
subgroup networks. Its print() shows the same quality line,
information criteria and subgroup table, without the state count, the
log-likelihood or the convergence line, and its plot() draws the same
two views as plot() of a net_mmm. The "silhouette", "mds" and
"heatmap" views of a dissimilarity-based clustering need a distance
matrix, which an MMM clustering does not have, so asking for them raises
an error.
References
Helske, S., & Helske, J. (2019). Mixture hidden Markov models for sequence data: The seqHMM package in R. Journal of Statistical Software, 88(3), 1–32. doi:10.18637/jss.v088.i03
Vermunt, J. K., & Magidson, J. (2005). Latent GOLD 4.0 User's Guide. Statistical Innovations.
See Also
Examples
seqs <- data.frame(V1 = sample(c("A","B","C"), 30, TRUE),
V2 = sample(c("A","B","C"), 30, TRUE))
mmm <- build_mmm(seqs, k = 2, n_starts = 1, max_iter = 10, seed = 1)
mmm
seqs <- data.frame(
V1 = sample(LETTERS[1:3], 30, TRUE), V2 = sample(LETTERS[1:3], 30, TRUE),
V3 = sample(LETTERS[1:3], 30, TRUE), V4 = sample(LETTERS[1:3], 30, TRUE)
)
mmm <- build_mmm(seqs, k = 2, seed = 42)
print(mmm)
summary(mmm)
Fit a multi-order generative model to sequences
Description
build_mogen() fits Markov chains of every order from 0 to max_order
to a set of sequences and selects the order that best balances fit
against the number of parameters, by AIC, BIC or likelihood-ratio tests.
At order k the chain is a De Bruijn graph: its nodes are the k-tuples of
consecutive states seen in the data, and an edge joins two tuples that
overlap in k - 1 states, so each edge is an observed path of k + 1
states. Order 0 is the marginal distribution of the states. It is the
multi-order model of Scholtes (2017), and takes wide sequence data, a
list of state vectors, a tna model or a network built from sequences.
The selected order is the number of earlier states the next state
depends on, as far as the sample can show. The number of parameters
grows quickly with the order (summary() lists them per order), so few
or short sequences favour low orders, and AIC and BIC can disagree:
print() shows both. Before reading a higher-order transition, check how
often its context was observed with mogen_transitions();
markov_order_test() tests the order against a permutation null, and
path_dependence() shows which contexts carry the extra information.
Usage
build_mogen(
data,
max_order = 5L,
criterion = c("aic", "bic", "lrt"),
lrt_alpha = 0.01,
dof = c("paths", "observed")
)
## S3 method for class 'net_mogen'
print(x, ...)
## S3 method for class 'net_mogen'
summary(object, ...)
## S3 method for class 'net_mogen'
plot(x, type = c("ic", "likelihood"), ...)
Arguments
data |
The sequences: a data frame with one row per trajectory and
one column per time point, a character matrix laid out the same way, a
list of state vectors (one per trajectory), a |
max_order |
The highest order fitted, a whole number of at least 1;
a value such as |
criterion |
How the order is selected: |
lrt_alpha |
The significance level of the likelihood-ratio tests,
strictly between 0 and 1. Default |
dof |
How the parameters of each layer are counted. |
x |
For the |
... |
For the |
object |
For the |
type |
For the |
Details
The log-likelihood of the order-k model scores the first state of each
trajectory by the marginal distribution, the j-th state by the order
j - 1 transitions while j <= k, and every later state by the order-k
transitions. The likelihood-ratio test of order k against order k - 1
refers twice the gain in log-likelihood to a chi-square distribution with
the order-k layer's degrees of freedom. The tests start from the
first-order model as the null (Scholtes 2017; pathpy 2
MultiOrderModel.estimate_order): order 1 is not tested against order 0,
because a first-order model restricted to the observed transitions does
not nest the order-0 model, so the p-value is NA for orders 0 and 1, and
also where the statistic or the degrees of freedom are not positive. With
criterion = "lrt" the selected order is the largest k of at least 2
whose test rejects at lrt_alpha, or 1 when none does; only AIC and BIC
can select order 0. Every p-value is kept in the result, so a
non-monotone run of tests is visible.
The model is the one pathpy 2 calls MultiOrderModel. It is not the
multi-order generative model of Gote et al. (2023), which adds start and
end states and selects by AIC only; the function name is kept for
compatibility.
Value
A net_mogen object (class c("net_mogen", "cograph_network")).
print() shows the selected order and the AIC and BIC of every order,
with each minimum starred. summary() prints the states and the
selection, then returns, visibly, one row per order as a data frame
(order, layer_dof, cum_dof, loglik, aic, bic, best
("AIC", "BIC" or "AIC+BIC" on the order each criterion picks,
empty elsewhere) and selected ("<--" on the chosen order)).
plot() draws the criteria or the log-likelihood against the order and
returns its input invisibly; print() also returns its input
invisibly. mogen_transitions() gives the transitions of one
order, one row per path, and pathways() the same as character
strings. The object's fields:
- optimal_order
The selected order.
- criterion
The criterion used for the selection.
- orders
The orders fitted, 0 to
max_orderafter any capping.- aic, bic, log_likelihood
Named numeric vectors, one value per order.
- dof
Named numeric vector of the cumulative degrees of freedom of each model.
- layer_dof
Named numeric vector of the degrees of freedom of each layer.
- dof_method
"paths"or"observed".- lrt_p
Named numeric vector: the likelihood-ratio p-value of order k against order k - 1 (
NAfor orders 0 and 1).- transition_matrices
List of row-stochastic transition matrices (a context never followed by another state keeps a zero row), the first (order 0) held as the named vector of marginal probabilities.
- count_matrices
List of the matching counts, in the same order, the first (order 0) as a named vector of state counts;
mogen_transitions()reads them.- states
The distinct first-order states.
- n_paths
Number of trajectories fitted.
- n_observations
Total number of state observations.
- weights
The transition matrix of the selected order, as the
cograph_networkweight matrix (when the selected order is 0, a states x states matrix of zeros, since an order-0 model has no transitions; its marginal is the first element oftransition_matrices). Its dimnames are internal k-tuple keys (states joined by a non-printing separator), not arrow notation.- nodes
Data frame (
id,label,name) of the nodes of the selected order (the states at order 0).- edges
The
cograph_networkedge data frame, with integerfromandtonode indices and a numericweight;mogen_transitions()gives the readable table.- directed
Always
TRUE.- n_nodes, n_edges
Counts for the graph of the selected order.
- meta
The
cograph_networkmetadata list.- node_groups
Always
NULL.
References
Scholtes, I. (2017). When is a Network a Network? Multi-Order Graphical Model Selection in Pathways and Temporal Networks. KDD 2017.
Gote, C., Casiraghi, G., Schweitzer, F., & Scholtes, I. (2023). Predicting variable-length paths in networked systems using multi-order generative models. Applied Network Science, 8, 68.
Examples
seqs <- list(c("A","B","C","D"), c("A","B","C","A"), c("B","C","D","A"))
mg <- build_mogen(seqs, max_order = 2)
trajs <- list(c("A","B","C","D"), c("A","B","D","C"),
c("B","C","D","A"), c("C","D","A","B"))
m <- build_mogen(trajs, max_order = 3)
print(m)
plot(m)
Estimate a network
Description
build_network() estimates a network from sequences, an event log,
one-hot codes or numeric variables, with the estimator named by method,
and returns a netobject: the object every other Nestimate verb reads
(bootstrap, permutation, centrality, clustering, plotting). Each method's
arguments are on its own page, named under method; they are given here
by name, as in build_network(df, method = "relative", actor = "id").
Column roles are declared, never read from names or values, and input
that fits none of the readings raises an error of class
nestimate_bad_input. The weights are point estimates: see how far they
move under resampling with bootstrap_network(), and compare groups with
permutation().
Usage
build_network(
data,
method,
...,
group = NULL,
scaling = NULL,
threshold = 0,
labels = NULL,
inherit = FALSE
)
## S3 method for class 'netobject'
print(x, n = 10L, ...)
## S3 method for class 'netobject_group'
print(x, digits = 3L, ...)
## S3 method for class 'netobject_ml'
print(x, ...)
## S3 method for class 'netobject'
summary(object, ...)
## S3 method for class 'netobject_group'
summary(object, combined = TRUE, format = c("long", "wide"), ...)
## S3 method for class 'summary.netobject'
print(x, ...)
## S3 method for class 'summary.netobject_group'
x[i, j, ...]
## S3 method for class 'summary.netobject_group'
print(x, ...)
Arguments
data |
The data the method reads (see its page), or a fitted
clustering ( | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
method |
The estimator. Each has its own page with its arguments:
The other names | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
... |
The method's arguments, by name, as listed on its page, such as
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
group |
A column to split the data by: one network per value,
returned as a | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scaling |
Rescaling applied to the weights after estimation, in the
order given: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
threshold |
Weights whose absolute value is below this are set to
zero. Default | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
labels |
New display labels for the nodes, applied after estimation:
a two-column data frame ( | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
inherit |
Only when | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
x |
For the | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
n |
For | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
digits |
For | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
object |
For | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
combined |
For | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
format |
For | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
i, j |
For |
Value
A netobject (class c("netobject", "cograph_network")). Print it
for an overview; extract_edges() gives one row per edge, extract_transition_matrix()
and extract_initial_probs() the weights and initial-state
probabilities, and cograph::splot() draws it. summary() returns the
descriptive metrics, one row per metric (a netobject_group gives one
row per metric and group, with a group column). The print() methods
return their input invisibly.
The netobject's fields:
- data
The state columns of the cleaned input data, as a data frame.
- metadata
Data frame of the non-state columns of the cleaned input (and, for long input, the per-sequence metadata), or NULL.
- weights
The estimated network weight matrix.
- nodes
Data frame with columns
id,label,name,x,y.- edges
Data frame of non-zero edges with integer
from/to(node IDs) and numericweight.- directed
Logical. Whether the network is directed.
- method
The resolved method name.
- params
The params list used (for reproducibility).
- scaling
The scaling applied (or NULL).
- threshold
The threshold applied.
- n_nodes
Number of nodes.
- n_edges
Number of non-zero edges.
- level
Decomposition level used, or NULL; for
mgmbuilt without a decomposition, the category count of each variable.- build_args
The resolved column/format arguments (
actor,action,time,session,order,codes,format,window_size,mode) used for this build.- meta
List with
source,layout, andtnametadata (cograph-compatible).- node_groups
Node groupings data frame, or NULL.
- predictability
Named numeric vector of R-squared predictability values per node, for
cor,pcorandglassowhenpredictability = TRUE; NULL otherwise.
The estimator's own results are kept beside these fields, depending on
the method: for example frequency_matrix and initial for relative,
frequency, ngram, gap and reverse (only initial for
attention, neither for co_occurrence), cor_matrix and the sample
size n for cor, pcor and glasso, precision_matrix for pcor
and glasso, and lambda_selected for glasso. A latency network
keeps initial, n_replies and median_latency (matrices laid out as
the weights), latency_cap_seconds (the resolved global cap, also in
params), latency_unit_caps (the per-unit caps of a non-global
latency_scope, named by unit, also in params) and latency_time, the
event times in seconds (and, for the "actor" and "session" scopes,
each sequence's unit), one row per row of data.
With level = "both", the result is a netobject_ml holding the
between-person and within-person networks (between and within, each a
netobject) and the method. level = "between" or "within" returns
a single netobject estimated on the decomposed data.
With group, or when data is a net_clustering or net_mmm object,
the result is a netobject_group: a named list of netobjects, one per
group, that records the grouping column in its group_col attribute.
Methods
Printing a netobject shows the kind of network, the range of its
weights (with the numbers of positive and negative edges for cor,
pcor, glasso and ising, the mean weight otherwise), the weight
matrix under the node labels, the initial probabilities and the
predictability values when present, the sample size for cor, pcor,
glasso and ising, the tuning values of glasso and ising, and any
scaling or threshold. Printing a netobject_group gives a header naming
its source (a clustering from build_network() on a net_clustering or
net_mmm fit, or cluster_network(), or a plain split by the grouping
column) and one row per group with its node and edge counts and weight
range; when the groups are clusters, it also shows the number and share
of sequences in each, in the layout of the build_clusters() and
build_mmm() prints. A netobject_ml prints the node, edge and sample
counts of its between- and within-person networks.
summary() gives the descriptive metrics tna::summary.tna() reports:
node and edge counts, density, mean shortest-path distance, the mean and
SD of out- and in-strength, the mean and SD of out-degree, out- and
in-degree centralisation (Freeman) and reciprocity. A self-loop counts as
an edge, and an undirected edge is counted once. Density divides the
edge count, self-loops included, by the n(n - 1) off-diagonal pairs
(n(n - 1) / 2 when undirected), as tna::summary.tna() and
igraph::edge_density(loops = FALSE) do, and is capped at 1.
Strengths sum absolute weights. Distances take each edge's absolute
weight as its length, not its inverse, and pairs with no path between
them are left out of the mean. Degree centralisation ignores self-loops,
and reciprocity is the share of off-diagonal edges whose reverse is also
present (1 for an undirected network). Mean distance and reciprocity are
NaN when no pair qualifies. Printing a summary shows the counts as
integers and the other metrics to four significant digits.
References
Saqr, M., López-Pernas, S., Törmänen, T., Kaliisa, R., Misiejuk, K., & Tikka, S. (2025). Transition network analysis: A novel framework for modeling, visualizing, and identifying the temporal patterns of learners and learning processes. In Proceedings of the 15th International Learning Analytics and Knowledge Conference (LAK25). ACM. doi:10.1145/3706468.3706513
See Also
list_estimators() and register_estimator() for the estimator
registry; bootstrap_network(), permutation() and net_centrality()
for what to do with the network.
Examples
build_network(trajectories, method = "relative")
build_network(group_regulation_long, method = "relative", actor = "Actor",
action = "Action", time = "Time", group = "Course")
build_network(trajectories, method = "attention", lambda = 2)
build_network(srl_strategies, method = "glasso", gamma = 0.25)
Estimate an n-gram transition network analysis model
Description
build_network(method = "ngram"), or for short build_ngram(),
estimates an n-gram transition network analysis model from windows of
n_gram consecutive states. Each window adds each of its adjacent pairs
once, so a pair inside a sequence is counted up to n_gram - 1 times, as
tna::build_model(type = "n-gram") counts it.
The weights are raw counts; add scaling = "normalize" for row
probabilities. With n_gram = 2 the network equals build_ftna().
Usage
build_ngram(
data,
start = FALSE,
end = FALSE,
actor = NULL,
action = NULL,
time = NULL,
session = NULL,
order = NULL,
time_threshold = 900,
timezone = "UTC",
state_cols = NULL,
metadata_cols = NULL,
n_gram = 2L,
group = NULL,
scaling = NULL,
threshold = 0,
labels = NULL,
params = list(),
...
)
Arguments
data |
The sequences: a data frame with one row per sequence and one
column per position, or an event log (one row per event, with |
start |
A start state put before every sequence, so the network
shows where sequences begin (an edge from it to each sequence's first
state). |
end |
An end state put in the cell after each sequence's last
observed state, so the network shows where sequences stop. It has no
outgoing edges and no self-loop, unlike |
actor |
The column naming who each row belongs to (a person, a
team). In an event log, each actor's events form a sequence, split
further by |
action |
The column holding each event's state; setting it declares
the data an event log. Column names give no role: |
time |
The timestamp column of an event log. Events are ordered by
it, and a gap longer than |
session |
The column identifying sessions in an event log; each
session is its own sequence, also without |
order |
The column that orders events sharing a timestamp; without
it, those events keep their row order. Default |
time_threshold |
The longest gap, in seconds, between two events of
the same sequence in an event log; a longer gap starts a new sequence.
|
timezone |
The Olson time zone for timestamps without an offset
(passed to |
state_cols |
The columns of a wide table that are sequence
positions; every other column goes to the network's metadata. Declared
columns are positions even when they hold only 0 and 1. With nothing
declared, the frame must be one column or hold position columns named
as a numbered run (a shared prefix and a number, |
metadata_cols |
Columns to keep as the network's metadata
(covariates), never as positions; they cannot overlap |
n_gram |
The window length, a whole number of at least 2. Default
|
group |
A column to split the data by: one network per value,
returned as a |
scaling |
Rescaling applied to the weights after estimation, in the
order given: |
threshold |
Weights whose absolute value is below this are set to
zero. Default |
labels |
New display labels for the nodes, applied after estimation:
a two-column data frame ( |
params |
Settings for the estimator, as a named list, as for
|
... |
Further arguments for |
Value
A netobject (a netobject_group with group), as
build_network() returns it.
References
Tikka, S., López-Pernas, S., & Saqr, M. (2025). tna: An R package for transition network analysis. Applied Psychological Measurement. doi:10.1177/01466216251348840
See Also
build_network() for every method; build_gap() and
build_reverse() for the other tna model types.
Examples
build_network(trajectories, method = "ngram", n_gram = 3)
build_ngram(trajectories, n_gram = 3)
Estimate a partial correlation network
Description
build_network(method = "pcor"), or for short build_pcor(), estimates
a partial correlation network of numeric variables. The edge between two
variables is their partial correlation given all the others, read from
the inverse of the correlation matrix, without regularisation (Epskamp &
Fried, 2018).
Unregularised partial correlations are noisy when there are many
variables for the number of observations, and they cannot be estimated
when the correlation matrix is singular (more variables than
observations, or collinear ones): that raises an error, and a
near-singular matrix a warning. build_glasso() estimates a sparse
network in those cases.
Usage
build_pcor(
data,
actor = NULL,
level = NULL,
...,
cor_method = c("pearson", "spearman", "kendall"),
predictability = TRUE,
metadata_cols = NULL,
group = NULL,
scaling = NULL,
threshold = 0,
labels = NULL,
params = list()
)
Arguments
data |
The variables: a data frame with one row per observation and
one column per variable, or a square symmetric correlation or
covariance matrix, which needs the sample size in |
actor |
The id column naming whose observation each row is (a
person). With |
level |
Multilevel decomposition, with |
... |
Further arguments for |
cor_method |
|
predictability |
Whether to compute each node's predictability (the
R-squared of the node on its neighbours). It is stored on the network,
and |
metadata_cols |
Columns to keep as the network's metadata
(covariates), never read as variables. Default |
group |
A column to split the data by: one network per value,
returned as a |
scaling |
Rescaling applied to the weights after estimation, in the
order given: |
threshold |
Weights whose absolute value is below this are set to
zero. Default |
labels |
New display labels for the nodes, applied after estimation:
a two-column data frame ( |
params |
Settings for the estimator, as a named list, such as |
Value
A netobject (a netobject_group with group, a netobject_ml
with level = "both"), as build_network() returns it.
References
Epskamp, S., & Fried, E. I. (2018). A tutorial on regularized partial correlation networks. Psychological Methods, 23(4), 617–634. doi:10.1037/met0000167
See Also
build_network() for every method; build_cor(),
build_glasso() and build_ising() for the other association
networks.
Examples
build_network(srl_strategies, method = "pcor")
build_pcor(srl_strategies)
Estimate a reverse transition network analysis model
Description
build_network(method = "reverse"), or for short build_reverse(),
estimates a reverse (reply) transition network analysis model: the edge
from state A to state B counts the times A comes right after B, so each
state points to the one it answers. It is the transpose of the frequency
network, as tna::build_model(type = "reverse") computes it.
The weights are raw counts; add scaling = "normalize" for row
probabilities. build_latency() weights the same replies by their speed.
Usage
build_reverse(
data,
start = FALSE,
end = FALSE,
actor = NULL,
action = NULL,
time = NULL,
session = NULL,
order = NULL,
time_threshold = 900,
timezone = "UTC",
state_cols = NULL,
metadata_cols = NULL,
weighted = FALSE,
group = NULL,
scaling = NULL,
threshold = 0,
labels = NULL,
params = list(),
...
)
Arguments
data |
The sequences: a data frame with one row per sequence and one
column per position, or an event log (one row per event, with |
start |
A start state put before every sequence, so the network
shows where sequences begin (an edge from it to each sequence's first
state). |
end |
An end state put in the cell after each sequence's last
observed state, so the network shows where sequences stop. It has no
outgoing edges and no self-loop, unlike |
actor |
The column naming who each row belongs to (a person, a
team). In an event log, each actor's events form a sequence, split
further by |
action |
The column holding each event's state; setting it declares
the data an event log. Column names give no role: |
time |
The timestamp column of an event log. Events are ordered by
it, and a gap longer than |
session |
The column identifying sessions in an event log; each
session is its own sequence, also without |
order |
The column that orders events sharing a timestamp; without
it, those events keep their row order. Default |
time_threshold |
The longest gap, in seconds, between two events of
the same sequence in an event log; a longer gap starts a new sequence.
|
timezone |
The Olson time zone for timestamps without an offset
(passed to |
state_cols |
The columns of a wide table that are sequence
positions; every other column goes to the network's metadata. Declared
columns are positions even when they hold only 0 and 1. With nothing
declared, the frame must be one column or hold position columns named
as a numbered run (a shared prefix and a number, |
metadata_cols |
Columns to keep as the network's metadata
(covariates), never as positions; they cannot overlap |
weighted |
Whether each pair is weighted by one over the length of
its sequence. Default |
group |
A column to split the data by: one network per value,
returned as a |
scaling |
Rescaling applied to the weights after estimation, in the
order given: |
threshold |
Weights whose absolute value is below this are set to
zero. Default |
labels |
New display labels for the nodes, applied after estimation:
a two-column data frame ( |
params |
Settings for the estimator, as a named list, as for
|
... |
Further arguments for |
Value
A netobject (a netobject_group with group), as
build_network() returns it.
References
Tikka, S., López-Pernas, S., & Saqr, M. (2025). tna: An R package for transition network analysis. Applied Psychological Measurement. doi:10.1177/01466216251348840
See Also
build_network() for every method; build_latency() for
replies weighted by speed.
Examples
build_network(trajectories, method = "reverse")
build_reverse(trajectories)
Build a simplicial complex
Description
build_simplicial() builds a simplicial complex, the higher-order
structure of a network: besides nodes (0-simplices) and edges
(1-simplices) it holds filled triangles (2-simplices), tetrahedra and
larger groups of nodes. Three constructions are available through type:
-
Clique complex (
"clique"): every clique of the network whose edges reachthresholdbecomes a simplex, the standard bridge from a graph to algebraic topology. -
Pathway complex (
"pathway"): the states on each higher-order pathway of anet_hon,net_hypaornet_mogen(or of one built from atnamodel ornetobject) become a simplex. -
Vietoris-Rips complex (
"vr", alias"rips"): the input is a non-negative distance matrix, every group of nodes whose pairwise distances are all at mostmax_scalebecomes a simplex, and each simplex records the scale at which it enters (its largest pairwise distance), sopersistent_homology()can read the filtration.
A clique complex is fixed by the thresholded graph, since every clique is
filled in; its Betti numbers count the holes that remain, such as cycles
of edges that no triangles fill. Its shape depends on threshold, so
read betti_numbers() at more than one threshold, or follow the features
across all of them with persistent_homology(). A pathway complex is
built from paths observed in the sequences, so its simplices say which
states occur together on a path.
simplicial_degree() and q_analysis() describe how the nodes take part
in the complex.
Usage
build_simplicial(
x,
type = "clique",
threshold = 0,
max_dim = 10L,
max_pathways = NULL,
anomaly = c("all", "over", "under"),
max_scale = NULL,
...
)
## S3 method for class 'simplicial_complex'
print(x, ...)
## S3 method for class 'simplicial_complex'
plot(x, combined = TRUE, ...)
Arguments
x |
The network: a square weight matrix, a |
type |
The construction: |
threshold |
For |
max_dim |
The highest simplex dimension built (a k-simplex has k + 1
nodes), a non-negative whole number. Default |
max_pathways |
For |
anomaly |
For |
max_scale |
For |
... |
For |
combined |
For the |
Details
For the clique and Vietoris-Rips complexes the weight matrix is made
symmetric first (the larger absolute weight of the two directions for a
clique complex, the larger distance for a Vietoris-Rips complex) and its
diagonal is not read. Cliques are found with igraph::cliques() when
igraph is installed, and by Bron-Kerbosch otherwise.
Value
A simplicial_complex object. print() shows the counts, the
density, the f-vector (simplices per dimension), the Euler
characteristic and the non-zero Betti numbers; plot() draws the
f-vector, the Betti numbers and the simplicial degree of each node;
betti_numbers(), euler_characteristic(), simplicial_degree(),
q_analysis() and persistent_homology() read it. The object's
fields:
- simplices
List of integer vectors, one per simplex, each holding the sorted indices of the nodes it spans. Every face of every simplex is present, as are all 0-simplices (isolated nodes included).
- nodes
Character vector of node labels, which
simplicesindex.- n_nodes, n_simplices
Counts of nodes and simplices.
- dimension
Highest simplex dimension present.
- f_vector
Named integer vector
dim_0,dim_1, ...: the number of simplices of each dimension.- density
n_simplicesdivided by the number of simplices a complete complex onn_nodesnodes would have up todimension.- mean_dim
Mean simplex dimension.
- type
"clique","pathway"or"vr".- truncated
For the clique and Vietoris-Rips complexes: whether
max_dimcut a larger clique.
A Vietoris-Rips complex also holds filtration (the scale at which each
simplex enters, in the order of simplices) and max_scale (the cap
used), which persistent_homology() reads.
The print() method returns its input invisibly. plot()
returns the drawn grid grob invisibly with combined = TRUE, and the
named list of four ggplots invisibly with combined = FALSE.
See Also
betti_numbers, persistent_homology,
simplicial_degree, q_analysis
Examples
mat <- matrix(c(0,.6,.5,.6,0,.4,.5,.4,0), 3, 3)
colnames(mat) <- rownames(mat) <- c("A","B","C")
sc <- build_simplicial(mat, threshold = 0.3)
print(sc)
betti_numbers(sc)
# Vietoris-Rips on a distance matrix:
d <- 1 - mat
diag(d) <- 0
sc_vr <- build_simplicial(d, type = "vr", max_scale = 0.6)
Estimate a transition network analysis (TNA) model
Description
build_network(method = "relative"), or for short build_tna(),
estimates a transition network analysis (TNA) model from sequences of
states. The edge from state A to state B is the probability that B comes
next after A: the A-to-B transitions divided by all transitions out of A
(Saqr et al., 2025).
A state's edges compare within its row, not across rows. The weights are
point estimates: check how far they move under resampling with
bootstrap_network(), and compare groups with permutation().
Usage
build_tna(
data,
start = FALSE,
end = FALSE,
actor = NULL,
action = NULL,
time = NULL,
session = NULL,
...,
order = NULL,
time_threshold = 900,
timezone = "UTC",
state_cols = NULL,
metadata_cols = NULL,
codes = NULL,
window_size = 3L,
mode = c("non-overlapping", "overlapping"),
group = NULL,
scaling = NULL,
threshold = 0,
labels = NULL,
params = list()
)
Arguments
data |
The sequences: a data frame with one row per sequence and one
column per position, an event log (one row per event, with |
start |
A start state put before every sequence, so the network
shows where sequences begin (an edge from it to each sequence's first
state). |
end |
An end state put in the cell after each sequence's last
observed state, so the network shows where sequences stop. It has no
outgoing edges and no self-loop, unlike |
actor |
The column naming who each row belongs to (a person, a
team). In an event log, each actor's events form a sequence, split
further by |
action |
The column holding each event's state; setting it declares
the data an event log. Column names give no role: |
time |
The timestamp column of an event log. Events are ordered by
it, and a gap longer than |
session |
The column identifying sessions in an event log; each
session is its own sequence, also without |
... |
Further arguments for |
order |
The column that orders events sharing a timestamp; without
it, those events keep their row order. Default |
time_threshold |
The longest gap, in seconds, between two events of
the same sequence in an event log; a longer gap starts a new sequence.
|
timezone |
The Olson time zone for timestamps without an offset
(passed to |
state_cols |
The columns of a wide table that are sequence
positions; every other column goes to the network's metadata. Declared
columns are positions even when they hold only 0 and 1. With nothing
declared, the frame must be one column or hold position columns named
as a numbered run (a shared prefix and a number, |
metadata_cols |
Columns to keep as the network's metadata
(covariates), never as positions; they cannot overlap |
codes |
The one-hot code columns (one per state, 1 when the state is
active); setting them declares one-hot data. Default |
window_size |
For one-hot data: how many consecutive rows form one
window. Default |
mode |
For one-hot data: |
group |
A column to split the data by: one network per value,
returned as a |
scaling |
Rescaling applied to the weights after estimation, in the
order given: |
threshold |
Weights whose absolute value is below this are set to
zero. Default |
labels |
New display labels for the nodes, applied after estimation:
a two-column data frame ( |
params |
Settings for the estimator, as a named list. Transitions
are counted with tna's |
Value
A netobject (a netobject_group with group), as
build_network() returns it: print it for an overview, read the edges
with extract_edges() and the weights with
extract_transition_matrix(), and draw it with cograph::splot().
References
Saqr, M., López-Pernas, S., Törmänen, T., Kaliisa, R., Misiejuk, K., & Tikka, S. (2025). Transition network analysis: A novel framework for modeling, visualizing, and identifying the temporal patterns of learners and learning processes. In Proceedings of the 15th International Learning Analytics and Knowledge Conference (LAK25) (pp. 351–361). ACM. doi:10.1145/3706468.3706513
Tikka, S., López-Pernas, S., & Saqr, M. (2025). tna: An R package for transition network analysis. Applied Psychological Measurement. doi:10.1177/01466216251348840
See Also
build_network() for every method; build_ftna(),
build_atna() and build_cna() for the other transition networks;
bootstrap_network() and permutation() for inference.
Examples
build_network(trajectories, method = "relative")
build_tna(trajectories)
build_tna(group_regulation_long, actor = "Actor", action = "Action",
time = "Time", group = "Course", threshold = 0.05)
Estimate a window transition network analysis (WTNA) model
Description
build_network(method = "wtna"), or for short build_wtna(), estimates
a window transition network analysis (WTNA) model from one-hot codes. The
rows are cut into windows of window_size rows, and the edge from code A
to code B counts the times B is active in the window after one where A is
active.
Windows do not cross actors (actor) or sessions (session).
build_network(method = "wtna_cooccurrence") counts the codes active in
the same window instead; wtna() returns both networks at once.
Usage
build_wtna(
data,
codes = NULL,
window_size = 3L,
mode = c("non-overlapping", "overlapping"),
type = c("frequency", "relative"),
actor = NULL,
session = NULL,
metadata_cols = NULL,
group = NULL,
scaling = NULL,
threshold = 0,
labels = NULL,
params = list(),
...
)
Arguments
data |
One-hot data: one row per time point and one column of 0 and 1 per code. |
codes |
The code columns (one per state, 1 when the state is
active). Default |
window_size |
How many consecutive rows form one window. Default
|
mode |
|
type |
|
actor |
The column naming who each row belongs to; windows do not
cross actors. Default |
session |
The column identifying sessions; windows do not cross
sessions. Default |
metadata_cols |
Columns to keep as the network's metadata, never
read as codes. Default |
group |
A column to split the data by: one network per value,
returned as a |
scaling |
Rescaling applied to the weights after estimation, in the
order given: |
threshold |
Weights whose absolute value is below this are set to
zero. Default |
labels |
New display labels for the nodes, applied after estimation:
a two-column data frame ( |
params |
Settings for the estimator, as a named list. The network
keeps them. Default |
... |
Further arguments for |
Value
A netobject (a netobject_group with group), as
build_network() returns it.
See Also
build_network() for every method; wtna() for the transition
and co-occurrence networks together; action_to_onehot() to turn an
event log into one-hot codes.
Examples
codes <- c("Reading", "Video", "Forum", "Quiz", "Coding", "Review")
build_network(learning_activities, method = "wtna", codes = codes,
actor = "student")
build_wtna(learning_activities, codes = codes, actor = "student")
Estimate the case-dropping stability of edge weights
Description
casedrop_reliability() measures how stable a network's edge weights are
when cases are left out. It re-estimates the network on random subsets
that drop each proportion in drop_prop of the cases, compares each
re-estimated edge vector with the original, and reports a CS-coefficient
for the edge weights: the largest proportion of cases that can be dropped
while the correlation between the original and the re-estimated edge
weights stays at or above threshold in at least certainty of the
iterations (the case-dropping CS-coefficient of Epskamp, Borsboom & Fried,
2018, applied to the edge weights). Beside the correlation it records the
mean, median and largest absolute change of the edge weights. The cases
are the sequences of a transition network and the rows of the data
otherwise. It takes a single network, or a netobject_group or an mcml,
whose networks are assessed one by one.
It complements centrality_stability(): that asks whether centrality
rankings are stable, this asks whether the edge-weight structure
itself is. For an mcml built from an edge list, where each row of the
data is one transition, this is case-dropping of edges.
The CS-coefficient is the largest proportion in drop_prop that passes,
so it can only be one of the values tried. A smaller proportion need not
have passed as well, so look at the correlation at every proportion, not
only at the CS-coefficient: summary() gives its mean, median and
quantiles (q025, q975) per proportion, and plot() draws it. A correlation near 1 can hide a
large change in a few edges, which the largest absolute change
(max_abs_dev) shows. Stability under case-dropping says the estimate
does not rest on a few cases; it gives no interval for a single edge,
which bootstrap_network() does.
Usage
casedrop_reliability(
x,
iter = 1000L,
drop_prop = seq(0.1, 0.9, by = 0.1),
threshold = 0.7,
certainty = 0.95,
method = c("spearman", "pearson", "kendall"),
include_diag = FALSE,
seed = NULL,
target = c("auto", "existing", "all"),
actor = NULL
)
## S3 method for class 'net_casedrop_reliability'
print(x, digits = 3, ...)
## S3 method for class 'net_casedrop_reliability'
summary(object, ...)
## S3 method for class 'net_casedrop_reliability_group'
print(x, ...)
## S3 method for class 'net_casedrop_reliability_group'
summary(object, drop_prop = NULL, ...)
## S3 method for class 'summary.net_casedrop_reliability_group'
print(x, ...)
## S3 method for class 'net_casedrop_reliability'
plot(x, combined = TRUE, ...)
## S3 method for class 'net_casedrop_reliability_group'
plot(
x,
metric = c("correlation", "mean_abs_dev", "median_abs_dev", "max_abs_dev"),
...
)
Arguments
x |
The network: a |
iter |
The number of random subsets drawn for each drop proportion,
at least 2. Default |
drop_prop |
The proportions of cases to drop, each strictly between
0 and 1, in any order. Default |
threshold |
The lowest correlation between the original and the
re-estimated edge weights for an iteration to count as stable, between
0 and 1. Default |
certainty |
The share of iterations that must reach |
method |
The correlation: |
include_diag |
Whether self-loops are part of the edge vector.
Default |
seed |
A number that makes the subsets reproducible. The session's
own random stream is left as it was. For a |
target |
The cells compared. |
actor |
The column identifying the actor each sequence belongs to
(for example |
digits |
For the |
... |
For the |
object |
For the |
combined |
For the |
metric |
For the |
Details
For each drop proportion p and each iteration, a subset of
n - \lfloor np \rfloor of the n cases is
drawn without replacement, the network is re-estimated with the
input's method, scaling and threshold, and the compared cells of the new
weight matrix are set against the same cells of the original. For
transition networks the per-sequence transition counts are computed once
and summed over each subset; other networks are re-estimated from the
subset of rows. A re-estimation that fails, or that loses a node (a
variable constant in the subset), leaves the iteration without values;
such iterations are counted in a warning of class
nestimate_resample_failed and count as below threshold.
With target = "auto", unscaled and unthresholded transition networks
compare only the existing edges: an absent transition cannot appear in a
subset, and the fixed zeros would inflate the correlation. Association
networks and scaled or thresholded networks compare all cells, because a
zero original weight can become non-zero once cases are dropped; set
target = "existing" to compare only the original edges there.
Value
A net_casedrop_reliability object. print() shows the
CS-coefficient and the mean and standard deviation of each metric at
each drop proportion; summary() returns that table in full, one row
per metric and drop proportion; plot() draws the metrics across the
drop proportions. A netobject_group or mcml gives a
net_casedrop_reliability_group, a named list of one result per
network: its print() gives each network's number of cases, number of
edges and CS-coefficient, its summary() one row per network at one
drop proportion, and its plot() one curve per network. The fields of
a single result:
csThe CS-coefficient: the largest drop proportion at which the correlation reaches
thresholdin at leastcertaintyof the iterations.0when no proportion passes;NAwhen the original edge weights do not vary (constant up to rounding error, relative to their size), so the correlation is undefined.summaryA data frame with one row per metric and drop proportion:
metric("mean_abs_dev","median_abs_dev","correlation","max_abs_dev"),drop_prop, and themean,sd,median,mad,q025andq975of the metric over the iterations.metricsThe per-iteration values: a named list of four matrices, one per metric, with one row per iteration and one column per drop proportion.
correlationsThe same matrix as the
correlationentry ofmetrics.drop_prop,threshold,certainty,iter,method,include_diagThe settings used.
n_casesThe number of cases resampled from: sequences for a transition network (actors with
actor), rows of the data otherwise.actorWith
actoronly: the actor column(s).n_edgesThe number of cells compared, set by
targetandinclude_diag.
The resolved target is kept as the result's target attribute.
When the original edge weights do not vary, a warning is given and the
result has cs = NA, a summary whose statistics are NA, and metric
matrices of NA.
The print() methods return their input invisibly. The
summary() method of a single result returns its summary field,
described above. The summary() method of
a group result returns a summary.net_casedrop_reliability_group data
frame with one row per network (named in the row names): n_edges and
the four metrics (cor, mean_abs_dev, median_abs_dev,
max_abs_dev) at the chosen drop proportion, each written as
"mean +/- sd"; its print() names that proportion. The plot()
methods return a ggplot; with combined = FALSE, the named list of
plots is returned invisibly. A single result is drawn as one panel per
metric, the mean across iterations as a line with a band of plus and
minus one standard deviation; a group result draws the chosen metric
with one line and band per network. On the correlation, a dashed line
marks threshold. A result whose CS-coefficient is undefined is drawn as a
panel that says so, and in a group such networks are left out and
named in the caption.
Nested data and actor
Case-dropping drops cases at random, so it treats them as independent
units. When the sequences are nested in actors (several sessions per
person), the remaining sequences of an actor stand in for the dropped
ones, and the CS-coefficient overstates the stability. With actor, a
case is an actor: drop_prop is the proportion of actors dropped, and
all sequences of a dropped actor leave together, as in
tna::estimate_cs(actor = ). With one sequence per actor the result is
that of actor = NULL. Raises nestimate_actor_missing when the actor column is absent or incomplete, and nestimate_actor_unsupported when the network is not a transition network.
References
Epskamp, S., Borsboom, D., & Fried, E. I. (2018). Estimating psychological networks and their accuracy: A tutorial paper. Behavior Research Methods 50(1), 195-212. doi:10.3758/s13428-017-0862-1
See Also
centrality_stability(), bootstrap_network().
Examples
set.seed(1)
seqs <- data.frame(
V1 = sample(LETTERS[1:4], 30, TRUE),
V2 = sample(LETTERS[1:4], 30, TRUE),
V3 = sample(LETTERS[1:4], 30, TRUE)
)
net <- build_network(seqs, method = "relative")
es <- casedrop_reliability(net, iter = 20, drop_prop = c(0.1, 0.3, 0.5),
seed = 1)
print(es)
Estimate the CS-coefficient of centrality indices
Description
centrality_stability() estimates how stable a network's centrality
indices are under case-dropping (Epskamp, Borsboom & Fried, 2018). For
each proportion in drop_prop, that share of the sequences (or, for
association networks, of the rows) is removed at random iter times,
the network is re-estimated on what is left, and its centralities are
correlated with those of the full network. The CS-coefficient of a
measure is the largest proportion that can be dropped while the
correlation stays at or above threshold in at least a certainty
share of the draws. It takes a netobject from build_network() of any
method, a bare cograph_network, or a netobject_group or mcml, whose
networks are assessed one by one.
The CS-coefficient says how well the nodes' centralities (their values,
or with method = "spearman" or "kendall" their ordering) survive the
loss of cases; Epskamp et al. (2018) suggest that it should
not be below 0.25, and preferably above 0.5, before centrality
differences are interpreted. It does not say whether two nodes differ in
centrality, nor how precise single edges are: check the edges with
bootstrap_network(), and for glasso networks the centrality
differences with boot_glasso().
Usage
centrality_stability(
x,
measures = c("InStrength", "OutStrength", "Betweenness"),
iter = 1000L,
drop_prop = seq(0.1, 0.9, by = 0.1),
threshold = 0.7,
certainty = 0.95,
method = "pearson",
centrality_fn = NULL,
loops = FALSE,
normalize = FALSE,
invert = TRUE,
normalize_diffusion = TRUE,
seed = NULL,
actor = NULL
)
## S3 method for class 'net_stability'
print(x, ...)
## S3 method for class 'net_stability_group'
print(x, ...)
## S3 method for class 'net_stability_group'
summary(object, ...)
## S3 method for class 'net_stability'
summary(object, ...)
## S3 method for class 'net_stability'
plot(x, ...)
Arguments
x |
The network: a |
measures |
The centrality measures to assess. The default is
|
iter |
The number of random subsets drawn at each drop proportion,
at least 2. Default |
drop_prop |
The proportions of cases to drop, each strictly between
0 and 1. Default |
threshold |
The correlation with the full network's centralities
that a draw must reach, between 0 and 1. Default |
certainty |
The share of draws at a drop proportion that must reach
|
method |
The correlation between the full and the subset
centralities: |
centrality_fn |
A function of your own that takes the weight matrix
and returns a named list of centrality vectors, such as
|
loops |
Whether self-loops (staying in a state) count. With |
normalize |
Whether to range-normalise every measure to 0–1, as
|
invert |
Whether a heavier edge is a shorter step in the
shortest-path measures (distance = 1 / weight), as in |
normalize_diffusion |
Whether to range-normalise |
seed |
An integer that makes the random subsets reproducible.
Default |
actor |
The column identifying the actor each sequence belongs to
(for example |
... |
For the |
object |
For the |
Details
For transition methods, per-sequence count matrices are computed once
and each draw only re-sums them; the network's scaling and threshold
are applied to every re-estimated network as to the original. For the
other methods the estimator is re-run on each subset with the network's
params. A network built with level is refused (error class
nestimate_multilevel_resampling): its stored data are already
decomposed and carry no id column to decompose a subset again.
The built-in measures are computed from the weight matrix
directly, without igraph, as in net_centrality(): strength from row
and column sums, betweenness and closeness from Floyd-Warshall shortest
paths. A network that rests on one sequence, or one-hot data with no
actor or session, has nothing to drop and raises an error of class
nestimate_single_sequence. Latency networks are not resampled: a
network built with method = "latency" raises an error of class
nestimate_latency_resampling.
Every draw counts towards certainty: a draw whose correlation is
undefined (the measure is constant in it), and a draw whose network
could not be estimated, count as not reaching threshold. Failed
estimates are reported in a warning of class
nestimate_resample_failed.
Measures without variance are handled by two different rules, both
long-standing behaviour. When some requested measures do not vary
across the nodes of the original network (or are undefined on it), they
are dropped, and the result covers only the retained ones. When every
requested measure is so, a warning of class nestimate_constant_measure
is issued and all requested names
are returned with a CS-coefficient of 0 and correlations that are all
NA. A measure counts as constant when its values span no more than
the square root of the machine epsilon relative to their size, so
"OutStrength" of a "relative" network with loops = TRUE, which is
1 for every node up to rounding error, is dropped rather than correlated
on that error. The same rule makes a measure constant in a draw an
undefined correlation.
Value
A net_stability object. print() shows the CS-coefficient of
each measure; summary() returns one row per measure and drop
proportion, with the mean and SD of the correlations (over the draws
where it is defined) and prop_above, the share of all draws that
reach threshold; plot() draws the mean correlation against the
proportion dropped, one line per measure with a band of one SD and a
dashed line at threshold, and returns the ggplot invisibly. For a
netobject_group or mcml, the result is a net_stability_group, a
named list of net_stability objects, one per network, whose print()
shows the CS-coefficients as a networks-by-measures table and whose
summary() stacks the per-network summaries with a leading group
column. The print() methods return their input invisibly. The
net_stability's fields:
- cs
The CS-coefficients, a named numeric vector with one per retained measure.
- correlations
A named list, one per retained measure, of
iterxlength(drop_prop)matrices of correlations.- measures
The measures assessed (see the rule for measures without variance under Details).
- drop_prop, threshold, certainty, iter, method
The settings used.
- actor, n_actors
With
actoronly: the actor column(s) and the number of actors cases were dropped from.
Nested data and actor
Case-dropping treats the cases it drops as independent. When the
sequences are nested in actors (several sessions per student), the
remaining sequences of an actor stand in for the dropped ones, and the
CS-coefficient overstates the stability. With actor, a case is an
actor: drop_prop is the proportion of actors dropped, and all sequences
of a dropped actor leave together, as in tna::estimate_cs(actor = ).
A proportion that drops no actor (n * p < 1, likely with few actors)
is not run and counts as not reaching threshold, with a warning of
class nestimate_drop_prop_skipped; one actor may remain. With one
sequence per actor, and proportions that drop at least one and leave at
least two, the result is that of actor = NULL. A
column that is absent or has missing values raises
nestimate_actor_missing, fewer than two actors nestimate_bad_actor,
and a network that is not a transition network
nestimate_actor_unsupported.
References
Epskamp, S., Borsboom, D., & Fried, E. I. (2018). Estimating psychological networks and their accuracy: A tutorial paper. Behavior Research Methods 50(1), 195-212. doi:10.3758/s13428-017-0862-1
See Also
net_centrality(), bootstrap_network(),
network_reliability(), build_network()
Examples
seqs <- data.frame(
T1 = c("plan", "code", "debug", "plan", "test", "code"),
T2 = c("code", "debug", "code", "plan", "code", "test"),
T3 = c("debug", "code", "plan", "code", "debug", "plan"),
T4 = c("test", "plan", "test", "debug", "plan", "code")
)
net <- build_network(seqs, method = "relative")
cs <- centrality_stability(net, iter = 10, drop_prop = 0.3, seed = 1)
set.seed(1)
seqs <- data.frame(
V1 = sample(LETTERS[1:4], 30, TRUE), V2 = sample(LETTERS[1:4], 30, TRUE),
V3 = sample(LETTERS[1:4], 30, TRUE), V4 = sample(LETTERS[1:4], 30, TRUE)
)
net <- build_network(seqs, method = "relative")
cs <- centrality_stability(net, iter = 20, seed = 42,
measures = c("InStrength", "OutStrength"))
print(cs)
Estimate the Bayesian certainty of transition network edges
Description
certainty() gives each edge of a transition-probability network a
posterior mean, standard deviation, credible interval and a decision on
whether the edge is certain, all in closed form, and returns them in the
layout of bootstrap_network(). It models the outgoing transitions of
each state as a Dirichlet-Multinomial process: with a Dirichlet prior of
concentration prior, the posterior for state i is
\mathrm{Dirichlet}(c_i + \mathrm{prior}), where c_i are its
transition counts, so each edge probability is marginally Beta. It reads a
netobject built with method = "relative", or a netobject_group of
them.
With inference = "stability", an edge is certain when the posterior
mass outside a band around its weight (consistency_range) is below
ci_level; with "threshold", when the mass below edge_threshold is.
Certainty says how precisely the observed counts pin an edge down, not
whether the edge survives resampling the sequences (bootstrap_network())
or holds across split halves (network_reliability()). Certainty and
bootstrap stability agree on homogeneous data. Certainty treats every
transition as independent, so it is over-confident when the sequences come
from a mixture of latent classes, the more so the longer they are; use
bootstrap_network() there.
Usage
certainty(
x,
prior = 0.5,
ci_level = 0.05,
inference = c("stability", "threshold"),
consistency_range = c(0.75, 1.25),
edge_threshold = NULL
)
## S3 method for class 'net_certainty'
print(x, ...)
Arguments
x |
The network: a |
prior |
The Dirichlet concentration added to every cell of the count
matrix, zero cells and self-loops included; a positive number. Default
|
ci_level |
The tail level, in (0, 1), of the equal-tailed credible
intervals and of the decision: an edge is certain when its posterior
mass (the |
inference |
The decision rule. |
consistency_range |
For |
edge_threshold |
For |
... |
For the |
Details
Nothing is resampled: the posterior quantities are Beta means, variances
and quantiles (stats::qbeta(), stats::pbeta()), so a call takes
milliseconds.
Value
For a netobject: a net_certainty object (class
c("net_certainty", "net_bootstrap")), so the net_bootstrap methods
work on it. print() lists up to five certain edges with the largest
absolute posterior means (with their intervals), then the prior, the
count of certain edges and the settings;
summary() returns one row per non-zero edge with columns from,
to, weight, mean, sd, p_value, sig, ci_lower and
ci_upper, plus cr_lower and cr_upper (the band) for
inference = "stability"; cograph::splot() draws it. The object has
the fields of a bootstrap_network() result: original (the input
network), mean, sd, p_values, significant (the weights of the
certain edges, zero elsewhere), ci_lower, ci_upper, cr_lower,
cr_upper (matrices), summary, model (the network of certain edges
only), method, params, ci_level, inference,
consistency_range and edge_threshold, plus prior,
ci_method = "analytic" and iter = NA (no iterations).
For a netobject_group: a named list of those objects, one per
network, a net_certainty_group, printed and summarised as a net_bootstrap_group
(summary() stacks the per-network tables with a group column).
The print() method returns its input invisibly.
References
Johnston, L. & Jendoubi, T. (2026). How Delivery Mode Reshapes Resource Engagement: A Bayesian Differential Network Analysis. TNA Workshop 2026.
See Also
bootstrap_network, bayes_compare,
network_reliability
Examples
seqs <- data.frame(V1 = c("A","B","A","C","B"), V2 = c("B","C","B","A","C"),
V3 = c("C","A","C","B","A"))
net <- build_network(seqs, method = "relative")
cert <- certainty(net)
cert
summary(cert)
Classify the states and structure of a Markov chain
Description
chain_structure() describes the qualitative structure of a
discrete-time Markov chain: the properties that depend only on which
transitions are possible (the support of the transition matrix), not on
any starting distribution. It classifies every state as absorbing,
recurrent or transient, finds the communicating classes and the period of
each recurrent state, says whether the chain is irreducible, aperiodic,
regular and reversible, and computes the hitting probabilities and, when
transient states exist, the probability that each ends in each closed
class (an absorbing state or a closed class of several states) and the
expected number of steps it takes to enter one. It reads a transition network, a tna model, a transition
matrix or sequences, and analyses a grouped network one network at a
time.
It is a diagnostic to run before trusting passage_time() or
markov_stability(). Both assume a regular chain (irreducible and
aperiodic), whose stationary distribution is unique; is_regular says
whether that holds. The structure follows the estimated matrix: a
transition never observed in the data counts as impossible, so a chain
estimated from few sequences can look reducible because a rare move was
not seen.
Usage
chain_structure(x, normalize = TRUE, tol = 1e-10)
## S3 method for class 'chain_structure'
print(x, ...)
## S3 method for class 'chain_structure'
plot(x, show_values = TRUE, digits = 2L, ...)
## S3 method for class 'chain_structure'
summary(object, table = c("states", "absorption"), ...)
## S3 method for class 'chain_structure_group'
print(x, ...)
## S3 method for class 'chain_structure_group'
summary(object, table = c("states", "absorption"), ...)
## S3 method for class 'summary_chain_structure'
print(x, ...)
Arguments
x |
The chain: a |
normalize |
Whether to rescale rows that do not sum to 1 so that
they do, with a warning, as |
tol |
The tolerance below which a transition probability counts as
zero when the support graph is built. Every structural result is read from that graph, and the absorption results from the chain with those transitions removed and each row rescaled to sum to 1. |
... |
Ignored, except by the |
show_values |
For the |
digits |
For the |
object |
For the |
table |
For |
Details
The fundamental-matrix absorption analysis follows Kemeny & Snell (1976),
with every closed class lumped into one absorbing state, so each
transient state's absorption probabilities sum to 1;
the hitting probabilities are the minimal non-negative solution of the
linear system in Norris (1997), solved over the states that can reach the
target. The diagonal of the hitting matrix uses the return-time
convention, the probability of returning to the state in one or more
steps, as markovchain::hittingProbabilities() does.
Value
A chain_structure object, or for a netobject_group a
chain_structure_group, a named list holding one chain_structure per network. print() shows
the chain-level properties (for a group, one block per network);
summary() returns a data frame (see Summary columns): for a
chain_structure, a summary_chain_structure data frame with one row per state, carrying the chain-level flags as attributes that its print() method shows above the table; for a
chain_structure_group, a plain data frame with one row per group and
state. plot() returns a ggplot heatmap of the hitting probabilities
(see Plot colours). The print() methods return their input
invisibly.
The fields of a chain_structure:
statesCharacter vector of state names.
classificationNamed character vector, one of
"absorbing","recurrent"or"transient"per state.communicating_classesList of state-name vectors, one per strongly connected component of the support graph.
recurrent_classesThe communicating classes that are closed (no transition leaves the class).
transient_classesThe communicating classes that are not closed.
absorbing_statesCharacter vector of states with
P[i, i]equal to 1, to within about 1.5e-8;toldoes not relax this.periodNamed integer vector: the period of each recurrent state,
NAfor transient states.is_irreducibleTRUEwhen there is exactly one communicating class.is_aperiodicTRUEwhen every recurrent state has period 1.is_regularis_irreducible && is_aperiodic.is_reversibleTRUEwhen the chain satisfies detailed balance against its stationary distribution;NAfor a chain that is not irreducible (no unique stationary distribution).hitting_probabilitiesn x nmatrix whose[i, j]entry is the probability of ever reachingjfromi, computed over the sametol-thresholded support graph asclassification, so the two agree: a state in a closed class has hitting probability 0 to every state outside it. The absorption probabilities and times use the same thresholded chain.absorption_probabilitiesn_transient x n_closedmatrix whose[i, j]entry is the probability that the chain started in transient stateiends in closed classj; each row sums to 1. An absorbing state is a column named after it; a closed class of several states is one column named by its states joined with+(for exampleB+C).NULLwhen the chain has no transient state.mean_absorption_timeNamed numeric vector of the expected number of steps each transient state takes to enter a closed class, whichever it is.
NULLwhenabsorption_probabilitiesis.PThe transition matrix analysed (after any row normalisation).
Plot colours
The plot() method draws the hitting-probability matrix as a heatmap,
with rows and columns ordered by communicating class (closed classes
first, larger classes before smaller ones) so the block structure is
visible. Cell colour runs from white (0) to dark blue (1) and encodes the probability of ever reaching the column state from the row state; the diagonal holds the probability of returning to the state in one or more steps. The state labels on both axes
name each state's class, as in Active (recurrent), and the subtitle
lists the chain-level properties. A
chain that is not irreducible shows zero entries between classes that
cannot reach each other; when every state ends in one absorbing state,
that state's column is all 1s.
Summary columns
summary() of a chain_structure returns one row per state, combining every per-state result:
-
state,classificationandperiod; -
persistence, the diagonal of the transition matrix; -
return_probability, the diagonal of the hitting matrix; -
sojourn_steps,1 / (1 - persistence)(Inffor an absorbing state); -
stationary_probability, for an irreducible chain; for a chain with transient states:
mean_absorption_time, the steps to enter a closed class (NAfor states that are not transient).
Probabilities are rounded to 4 decimals and step counts to 2.
summary(table = "absorption") returns one row per transient state and
closed class: state, class (the class's states joined by +) and
probability, the probability of ending in that class, unrounded; no
rows when the chain has no transient state.
Columns are ordered for readability: identifiers first, classification
second, per-state results last.
summary() of a chain_structure_group stacks these tables into one
data frame with a group column first, one row per group and state (or
state and class); a column that only some groups have is NA for the
others.
References
Kemeny, J. G. and Snell, J. L. (1976). Finite Markov Chains. Springer-Verlag.
Norris, J. R. (1997). Markov Chains. Cambridge University Press.
See Also
passage_time(), markov_stability(), build_network()
Examples
net <- build_network(as.data.frame(trajectories), method = "relative")
cs <- chain_structure(net)
print(cs)
summary(cs)
ChatGPT scores on self-regulated learning scales
Description
chatgpt_srl is a dataset of the scores on five self-regulated learning
(SRL) scales of 1,000 responses that ChatGPT generated to a validated SRL
questionnaire, one row per response and one column per scale. The data are
part of a larger set comparing the responses of seven large language
models with human norms.
Usage
chatgpt_srl
Format
A data frame with 1,000 rows and 5 columns, one row per
response; each column is the numeric mean of one scale's items (13
items for CSU, 4 for TA and 9 for each of the others), with
observed values from 2 to 6.5 and no missing values:
- CSU
Cognitive Strategy Use.
- IV
Intrinsic Value.
- SE
Self-Efficacy.
- SR
Self-Regulation.
- TA
Test Anxiety.
Source
Vogelsmeier, L.V.D.E., Oliveira, E., Misiejuk, K., Lopez-Pernas, S., & Saqr, M. (2025). Delving into the psychology of Machines: Exploring the structure of self-regulated learning via LLM-generated survey responses. Computers in Human Behavior, 173, 108769. doi:10.1016/j.chb.2025.108769
Examples
net <- build_network(chatgpt_srl, method = "glasso",
params = list(gamma = 0.5))
net
Project a hypergraph onto a pairwise network
Description
clique_expansion() projects a hypergraph onto an ordinary pairwise
network, its clique expansion (also called the "downgrade" of a
hypergraph to a dyadic graph): each hyperedge links every pair of its
members, and the weight between two nodes sums these links over the
hyperedges. It takes a net_hypergraph from build_hypergraph() or
bipartite_groups() and returns an undirected
netobject. With binary incidence, the weight W[i, j]
is the number of hyperedges containing both i and j; with weighted
incidence, it is the sum over hyperedges of the product of the two
members' incidence values.
The projection keeps which pairs co-occur and how often, and drops the
groups themselves: three hyperedges {A, B}, {B, C} and {A, C} give
the same network as one hyperedge {A, B, C}. Read its edges as
pairwise co-occurrence; hypergraph_measures() and
hypergraph_centrality() work on the groups.
Usage
clique_expansion(hg, weighted = TRUE)
Arguments
hg |
A hypergraph, from |
weighted |
Whether to use the hypergraph's incidence values. With
|
Details
The weight matrix is computed in one BLAS call, tcrossprod(incidence),
in O(n_nodes^2 * n_hyperedges) time. With binary incidence (an
unweighted hypergraph, or weighted = FALSE), its off-diagonal counts
are those of cooccurrence() on the same groups, which also keeps the
diagonal.
Value
A netobject (class c("netobject", "cograph_network")) with
method "clique_expansion", undirected. print(), summary(),
extract_edges(), net_centrality() and cograph::splot() read it as
any network from build_network(). It carries no data, so the
resampling verbs, such as bootstrap_network(), and sequence
clustering refuse it. Its weight matrix is
W = incidence %*% t(incidence) with a zero diagonal, and it holds the
standard netobject fields (weights, nodes, edges, n_nodes,
n_edges, meta). edges has one row per non-zero upper-triangle
cell, with integer from/to node indices and weight. params
records source, weighted, n_hyperedges and
hypergraph_size_distribution.
Note
Experimental. Validated against tcrossprod(incidence) with a zero
diagonal. No external R package exposes clique expansion as a primitive;
the implementation restates the definition in one line.
References
Tian, H., & Zafarani, R. (2024). Higher-order networks representation and learning: A survey. ACM SIGKDD Explorations Newsletter 26(1), 1-18.
See Also
build_hypergraph(), bipartite_groups(), build_network().
Examples
df <- data.frame(
player = c("A", "B", "C", "A", "B", "D", "C", "D", "E"),
session = c("S1", "S1", "S1", "S2", "S2", "S3", "S3", "S3", "S3")
)
hg <- bipartite_groups(df, player = "player", group = "session")
net <- clique_expansion(hg)
extract_edges(net, threshold = 1)
Compare clusterings across k, dissimilarities and methods
Description
cluster_choice() clusters the same sequences under every combination of
the cluster counts, dissimilarities and algorithms given, each with
build_clusters(), and returns one row per combination with its average
silhouette width, mean within-cluster distance and cluster-size balance.
It is the distance-based counterpart of compare_mmm(), which compares
mixtures of Markov chains across k. "all" expands dissimilarity or
method to every supported option.
The silhouette of a sequence (Rousseeuw, 1987) compares its mean distance
to its own cluster with that to the nearest other cluster: near 1 it sits
well inside its cluster, near 0 between two, and below 0 it is closer to
another cluster. Rows that share a dissimilarity compare k and algorithms
on one distance scale; across dissimilarities the silhouettes and
within-cluster distances rest on different distances and compare less
directly. The row with the highest silhouette is marked, but that is not
a decision: also weigh the cluster sizes (min_size, size_ratio), as
a high silhouette can come with a cluster of very few sequences; then
fit the chosen configuration with build_clusters() and read it with its
summary(), plot() and cluster_diagnostics().
Usage
cluster_choice(
data,
k = 2:5,
dissimilarity = "hamming",
method = "ward.D2",
...
)
## S3 method for class 'cluster_choice'
print(x, digits = 3L, ...)
## S3 method for class 'cluster_choice'
summary(object, ...)
## S3 method for class 'cluster_choice'
plot(
x,
type = c("auto", "lines", "bars", "heatmap", "tradeoff", "facet"),
abbrev = FALSE,
combined = TRUE,
...
)
Arguments
data |
The sequences, passed to |
k |
The cluster counts to try. Default |
dissimilarity |
The dissimilarity measures to try. Default
|
method |
The clustering algorithms to try. Default |
... |
Further arguments of |
x |
For the |
digits |
For the |
object |
For the |
type |
For the |
abbrev |
For the |
combined |
For |
Value
A cluster_choice (a data frame subclass) with one row per
combination, k varying fastest, then dissimilarity, then method.
print() shows the table, with only the settings that vary as columns,
and flags the row with the highest silhouette in a best column;
summary() returns the full table as a plain data frame with a
character best column that holds "silhouette" on that row;
plot() draws the silhouette across the swept settings (see Plot
types) and returns the ggplot invisibly (with type = "facet" and
combined = FALSE, a named list of ggplots, returned invisibly and
not drawn). The print() method returns its input invisibly. The
columns:
- k, dissimilarity, method
The configuration of the row.
- silhouette
The average silhouette width over all sequences, computed by
build_clusters()(fromcluster::pam()for"pam", withcluster::silhouette()otherwise).- mean_within_dist
The mean distance between members of the same cluster, averaged over clusters weighted by their size (a one-member cluster counts as 0), in the units of the row's dissimilarity.
- min_size, max_size, size_ratio
The sizes of the smallest and the largest cluster, and their ratio
max_size / min_size.
Plot types
The plots show the values only: they carry no "best" marker and no
recommendation. plot() needs at least one swept setting.
"auto"The default. Picks a type from the swept settings:
"lines"when k is swept with at most one other setting,"bars"when onlydissimilarityor onlymethodis swept,"heatmap"when both are swept at a single k, and"facet"when all three are swept."lines"The silhouette across k, one line per value of the other swept setting. When only k is swept,
mean_within_distis drawn as a second line on the same axis. With all three swept, the lines followdissimilarityand the methods share them; use"facet"instead. Needs k swept."bars"Horizontal bars of the silhouette per value of the swept setting, or per combination when several are swept, sorted by silhouette, with the values printed.
"heatmap"Tiles of the silhouette over
dissimilarityandmethod, with the values printed. Needs both swept, and is meant for a single k."tradeoff"The silhouette against
size_ratio, each point labelled with its swept settings."facet"The silhouette across k, one line per dissimilarity and one panel per method. Needs all three swept.
References
Rousseeuw, P. J. (1987). Silhouettes: A graphical aid to the interpretation and validation of cluster analysis. Journal of Computational and Applied Mathematics, 20, 53–65. doi:10.1016/0377-0427(87)90125-7
See Also
build_clusters, compare_mmm for
the model-based equivalent, cluster_diagnostics for
the post-fit diagnostic surface on a single clustering.
Examples
seqs <- data.frame(V1 = sample(c("A","B","C"), 40, TRUE),
V2 = sample(c("A","B","C"), 40, TRUE))
cluster_choice(seqs, k = 2:4)
# Sweep dissimilarities at fixed k
cluster_choice(seqs, k = 3, dissimilarity = c("hamming", "lcs", "jaccard"))
# Full grid of k x dissimilarity
cluster_choice(seqs, k = 2:4, dissimilarity = c("hamming", "lcs"))
# "all" sentinel
cluster_choice(seqs, k = 3, dissimilarity = "all")
Cluster sequences (deprecated)
Description
cluster_data() is the old name of build_clusters(), renamed in
Nestimate 0.4.3. It is kept so older tutorials and the historical pkgdown
reference still run: every call raises a deprecation warning and passes
its arguments to build_clusters() unchanged.
Usage
cluster_data(...)
Arguments
... |
Arguments passed unchanged to |
Value
The net_clustering object that build_clusters() returns.
See Also
build_clusters, cluster_network,
cluster_mmm.
Collect the quality measures of a clustering
Description
cluster_diagnostics() collects the quality measures of a clustering in
one net_cluster_diagnostics object, laid out the same way whichever
route produced the clusters: a distance clustering from
build_clusters(), a mixed Markov model from build_mmm() or
cluster_mmm(), the netobject_group that cluster_network() or
build_network() builds from one of them, or the net_mmm_clustering
attribute of such a group. It packages what the fit already computed and
adds only the per-cluster summaries the fit does not store (silhouette
means and mean within-cluster distances for a distance clustering, the
classification error within each cluster for a mixture); it does not
refit.
For a distance clustering it reports the average silhouette width, overall and per cluster, and each cluster's mean within-cluster distance. For a mixture it reports each cluster's average posterior probability (AvePP) and mixing proportion, the overall AvePP, the normalised entropy of the posterior probabilities (0 when every sequence is assigned with certainty, 1 when all assignments are equally likely; the reverse of the relative entropy often reported for latent class models), the classification error (the expected share of sequences misclassified when each is assigned to its most likely cluster: one minus the largest posterior, averaged over all sequences and over each cluster's members, so it equals one minus the AvePP; Vermunt & Magidson, 2005), and the log-likelihood with BIC, AIC and ICL.
These measures describe how cleanly one solution separates the
sequences; none of them picks the number of clusters. Compare solutions
with cluster_choice() for distance clustering or compare_mmm() for
mixtures, and build the clusters' networks with build_network() on the
clustering to see how they differ, with bootstrap_network() for how
stable their edges are.
Usage
cluster_diagnostics(x, ...)
## S3 method for class 'net_cluster_diagnostics'
print(x, digits = 3L, ...)
## S3 method for class 'net_cluster_diagnostics'
plot(x, type = NULL, ...)
## S3 method for class 'net_cluster_diagnostics'
summary(object, ...)
Arguments
x |
The clustering: a |
... |
Not used: an extra argument raises an error, here and in the
|
digits |
For |
type |
For |
object |
For the |
Value
A net_cluster_diagnostics object. print() shows the numbers
of sequences and clusters (with the method and dissimilarity of a
distance clustering, or the number of states of a mixture), the overall
quality measures, the information criteria of a mixture, one row per
cluster, and the covariates of the fit, if any; plot() draws the clustering's own views. The object's
fields:
- family
"distance"or"mmm".- k, n, sizes
Number of clusters, number of sequences, and the cluster sizes.
- per_cluster
Data frame with one row per cluster; its columns depend on the family. Distance:
cluster,size,pct,mean_within_dist,sil_mean. Mixture:cluster,size,pct,mix_pct,avepp,class_err_pct.pct,mix_pctandclass_err_pctare in percent.- overall
List of the family's summary measures:
silhouettefor distance;avepp_overall,entropyandclassification_error(a proportion) for a mixture.- ics
For a mixture, a list with
BIC,AIC,ICLandlog_likelihood; NULL for distance.- metadata
The settings of the fit. Distance:
method,dissimilarity,weighted,lambda,medoids,covariates. Mixture:states,n_states,iterations,converged,covariates.- source
The clustering object itself, which
plot()draws without recomputing anything.
For print(): the input, invisibly. For plot(): what the
clustering's own plot() method returns, a ggplot object (invisibly)
or, for the covariate views with combined = FALSE, a list of
ggplot objects named by cluster (invisibly). For summary():
the per-cluster table described under per_cluster, a data frame with
one row per cluster.
References
Vermunt, J. K., & Magidson, J. (2005). Latent GOLD 4.0 User's Guide. Statistical Innovations.
See Also
build_clusters, build_mmm,
cluster_choice,
compare_mmm for k-sweep model selection (MMM only).
Examples
seqs <- data.frame(V1 = sample(c("A","B","C"), 30, TRUE),
V2 = sample(c("A","B","C"), 30, TRUE))
cl <- build_clusters(seqs, k = 2, method = "ward.D2")
cluster_diagnostics(cl)
fit <- cluster_mmm(seqs, k = 2, n_starts = 1, max_iter = 20, seed = 1)
cluster_diagnostics(fit)
summary(cluster_diagnostics(fit))
Cluster sequences with a mixed Markov model
Description
cluster_mmm() clusters sequences by fitting a mixture of first-order
Markov chains and returns the fitted net_mmm object: the same fit, with
the same arguments, as build_mmm(). The fit holds each sequence's
subgroup and posterior probabilities, the mixing proportions, the
information criteria and the subgroups' transition matrices.
Pass the fit to build_network() to get one network per subgroup, or use
cluster_network(..., cluster_by = "mmm") to fit and build the networks
in one call. build_mmm() explains how to read the fit and what to check
before trusting it.
Usage
cluster_mmm(
data,
k = 2L,
n_starts = 50L,
max_iter = 200L,
tol = 1e-06,
smooth = 0.01,
seed = NULL,
covariates = NULL,
covariate_effect = c("em", "posthoc"),
estimator = c("auto", "firth", "multinom", "chisq"),
cluster_by = "mmm",
...
)
Arguments
data |
The sequences: a data frame with one row per sequence and one
column per position, a |
k |
The number of subgroups (mixture components), a whole number of
at least 2. Default |
n_starts |
How many starting configurations to try, a positive whole
number. More starts make it likelier that the best local maximum is
found. Default |
max_iter |
The most EM iterations a start may run, a positive whole
number. Default |
tol |
The convergence tolerance: EM stops when the log-likelihood
changes by less than this between iterations (with |
smooth |
A pseudo-count added to every transition count before the
matrices are estimated, so a transition unseen in a subgroup gets a small
probability instead of zero. A finite non-negative number; default
|
seed |
An integer that makes the random starts reproducible.
Default |
covariates |
Variables describing each sequence (such as a course or
a grade), given as a column name, a character vector of names, a
one-sided formula or a data frame, as in |
covariate_effect |
How |
estimator |
How the after-fit multinomial logit is estimated; it never
affects the EM. |
cluster_by |
The clustering family. Only |
... |
Not used; any extra argument raises an error. |
Details
cluster_mmm() takes the arguments of build_mmm() plus cluster_by, so
its call has the same shape as cluster_network().
Value
A net_mmm object, exactly as build_mmm() returns it: print(),
summary() and plot() read it, build_network() gives one network per subgroup, cluster_diagnostics() the quality of the classification and, for sequences
built from long data with actor/session, session_ids() gives each
sequence's subgroup. build_mmm() lists its fields. For HTNA input,
the actor partition is kept and restored when the fit is turned into
networks with build_network() or as_htna().
See Also
build_mmm(), build_network(), and cluster_network() for
fitting and building the per-cluster networks in one call.
Examples
seqs <- data.frame(V1 = sample(c("A","B","C"), 30, TRUE),
V2 = sample(c("A","B","C"), 30, TRUE))
fit <- cluster_mmm(seqs, k = 2, n_starts = 1, max_iter = 10, seed = 1)
fit
cluster_diagnostics(fit)
# Visualise with sequence_plot
seqs <- data.frame(
V1 = sample(LETTERS[1:3], 40, TRUE),
V2 = sample(LETTERS[1:3], 40, TRUE),
V3 = sample(LETTERS[1:3], 40, TRUE)
)
fit <- cluster_mmm(seqs, k = 2)
sequence_plot(fit, type = "index")
Cluster sequences and estimate one network per cluster
Description
cluster_network() clusters a set of sequences and estimates one network
per cluster in a single call. It runs build_clusters() (dissimilarity
clustering with PAM or a hierarchical method) or, with
cluster_by = "mmm", build_mmm() (a mixture of Markov chains), then
build_network() on each cluster's sequences. The network method is
the method given in ...; without one, a netobject input passes on
its own method, so the per-cluster networks are of the same type as the
input, and other input gives "relative" transition networks. The
networks are built afresh: the input network's threshold, scaling and
estimator settings are used only with inherit = TRUE.
The clusters were formed to make the sequences within each one alike, so
their networks differ partly by construction. Check the classification
with cluster_diagnostics() and the choice of k with
cluster_choice() or compare_mmm(), and see how far each cluster's
edges move under resampling with bootstrap_network() before reading
differences between the networks.
Usage
cluster_network(
data,
k,
cluster_by = "pam",
dissimilarity = "hamming",
inherit = FALSE,
...
)
Arguments
data |
The sequences: a data frame, matrix, |
k |
The number of clusters, a whole number from 2 to one less than the number of sequences. Required. |
cluster_by |
The clustering algorithm. |
dissimilarity |
The distance between sequences, as in |
inherit |
When |
... |
Arguments for the two stages, routed by name. For
dissimilarity clustering, |
Details
method, the estimators' own arguments (such as n_gram or
direction) and build_network()'s threshold, scaling, start,
end and params reach the per-cluster networks. With
cluster_by = "mmm" and the default relative networks, which are the
fitted chains, scaling and threshold are applied to the fitted
weights, and an estimator argument, start, end or a new params
raises an error of class nestimate_bad_input. For a one-hot netobject
the stored build arguments are not used. Under "mmm", rebuilding a
network built from
long-format data with any method other than "relative" currently raises
an error, because its column names are passed on to the wide per-cluster
data. Per-cluster "latency" networks are not available (a clustering
keeps the sequences, not the event times): a latency network needs
another method here, or the error has class nestimate_latency_clusters.
Value
A netobject_group: one netobject per cluster, named
"Cluster 1", "Cluster 2", and so on, with the clustering (a
net_clustering, or for "mmm" a net_mmm_clustering) kept as
its "clustering" attribute. print() names the clustering method and
shows each cluster's network size, weight range and share of the
sequences; cluster_diagnostics() reads the clustering, and
summary() (the networks' metrics, a column per cluster),
bootstrap_network() and net_centrality() take the group as it is.
See Also
build_clusters, cluster_mmm,
build_network
Examples
seqs <- data.frame(V1 = c("A","B","C","A","B"), V2 = c("B","C","A","B","A"),
V3 = c("C","A","B","C","B"))
grp <- cluster_network(seqs, k = 2)
grp
set.seed(1)
seqs <- data.frame(
V1 = sample(LETTERS[1:4], 50, TRUE), V2 = sample(LETTERS[1:4], 50, TRUE),
V3 = sample(LETTERS[1:4], 50, TRUE), V4 = sample(LETTERS[1:4], 50, TRUE)
)
# Default: PAM clustering, relative (transition) networks
grp <- cluster_network(seqs, k = 3)
# MMM-based clustering
grp <- cluster_network(seqs, k = 2, cluster_by = "mmm")
Aggregate a network's weights to clusters of nodes
Description
cluster_summary() aggregates a node-level weight matrix to clusters of
nodes and returns an mcml object with two levels: a macro network whose
entry (i, j) combines every edge from a node of cluster i to a node of
cluster j (the diagonal combines the edges inside a cluster), and one
within-cluster network per cluster, the submatrix of its nodes. It takes a
weight matrix, a netobject, a bare cograph_network or a tna model,
and the clusters as a membership vector, a node-to-cluster data frame or a
named list. This is the matrix route of Multi-Cluster Multi-Level (MCML)
analysis; build_mcml() calls it for matrix input.
The macro weights are arithmetic aggregates (see method) of weights that
already exist. They are not row-normalised and are not the transition
probabilities of a process over clusters: the transitions between
clusters can be counted only from the sequences, which build_mcml()
does (its default type = "tna" gives transition probabilities between
clusters). as_tna() keeps the macro weights as
they are and does not normalise them.
Usage
cluster_summary(
x,
clusters = NULL,
method = c("sum", "mean", "median", "max", "min", "density", "geomean"),
directed = TRUE,
compute_within = TRUE
)
Arguments
x |
The node-level network: a numeric square matrix whose row and
column names (identical, in the same order) label the nodes, with
finite weights such as transition counts, co-occurrence frequencies or
probabilities; a |
clusters |
The cluster of each node, required (
Every node must belong to exactly one cluster: an unknown node, a node listed twice, a node left out or an empty cluster raises an error. |
method |
How the edges between (or within) two clusters are combined
into one weight, with
|
directed |
Whether the network is directed, so that A->B and B->A are
separate edges. Default |
compute_within |
Whether to build the within-cluster networks, one
n_i x n_i matrix per cluster. Default |
Details
Workflow
A typical MCML analysis:
# 1. Create the node-level network net <- build_network(data, method = "relative") # 2. Aggregate its edges to cluster level (arithmetic aggregation) cs <- cluster_summary(net, clusters = group_assignments, method = "sum") # 3. Read the result print(cs) # macro weights summary(cs) # one row per cluster # 4. Promote the layers to netobjects for downstream verbs nets <- as_tna(cs)
The macro matrix
The macro matrix has clusters as both rows and columns. An off-diagonal entry (i, j) is the aggregated weight from cluster i to cluster j; a diagonal entry (i, i) aggregates the edges inside cluster i.
Rows are not normalised: each entry is the aggregate method produces.
Row-normalising an arithmetic aggregate here (the old type = "tna"
combined with method = "min", "mean" and so on) gave rows that sum to
1 but are not a probability distribution over any process, which is why
type was removed from the matrix route. The sequence and edge-list
routes of build_mcml() keep type: there the aggregate is always a
count, and type chooses between well-defined network constructions.
Choosing method
| Input data | Suggested method | Reason |
| Edge counts | "sum" | Keeps the total flow between clusters |
| Transition matrix | "mean" | Avoids cluster-size bias |
| Correlation matrix | "mean" | Average correlations |
| Dense weighted | "max" / "median" | Less sensitive to single weights |
Value
An mcml object. Print it for the aggregation method, the node
and cluster counts, the clusters and the macro weights; summary()
returns a data frame with one row per cluster with its size, total absolute
within-cluster weight and between-cluster weight sent and received
(described under build_mcml());
as_tna() turns the layers into a netobject_group;
simplicial_features() summarises the topology of each within-cluster
network. macro_network(), which opens chosen clusters into their
states, needs an mcml built from sequences by build_mcml(); on this
result it raises an error of class nestimate_no_expand_source. The
object's fields:
- macro
The cluster-level layer (class
mcml_layer):weights, the k x k matrix of aggregated weights, diagonal included and rows not normalised;inits, the column sums of that matrix normalised to sum to 1 (equal shares when every weight is zero);labels, the cluster names; anddata,NULLon this route.- clusters
A named list of one
mcml_layerper cluster: the n_i x n_i submatrix of its nodes, self-loops included, and its normalised column sums asinits(1 for a single-node cluster).NULLwhencompute_within = FALSE.- cluster_members
A named list of each cluster's node labels, such as
list(A = c("n1", "n2"), B = c("n3", "n4", "n5")).- edges
NULL: a matrix carries no node-level transitions. The sequence and edge-list routes ofbuild_mcml()fill it.- meta
A list with
type(always"aggregate"here),method,directed,n_nodes,n_clusters,cluster_sizes(a named integer vector) andsource("matrix").
See Also
build_mcml to build an mcml from raw transitions instead
of a weight matrix,
as_tna to promote the layers to netobjects,
macro_network for the cluster-level network with one
cluster expanded back into its member states
Examples
# -----------------------------------------------------
# Basic usage with matrix and cluster vector
# -----------------------------------------------------
set.seed(1)
mat <- matrix(runif(100), 10, 10)
rownames(mat) <- colnames(mat) <- LETTERS[1:10]
cs <- cluster_summary(mat, c(1, 1, 1, 2, 2, 2, 3, 3, 3, 3))
cs # cluster-level (macro) weights
summary(cs) # one row per cluster
# -----------------------------------------------------
# Named list clusters (more readable)
# -----------------------------------------------------
clusters <- list(
Alpha = c("A", "B", "C"),
Beta = c("D", "E", "F"),
Gamma = c("G", "H", "I", "J")
)
cluster_summary(mat, clusters)
# -----------------------------------------------------
# A netobject as input: its weight matrix is aggregated
# -----------------------------------------------------
seqs <- data.frame(
T1 = c("A", "C", "B", "D"), T2 = c("B", "D", "A", "C"),
T3 = c("C", "A", "D", "B")
)
net <- build_network(seqs, method = "relative")
cluster_summary(net, list(G1 = c("A", "B"), G2 = c("C", "D")))
# -----------------------------------------------------
# Different aggregation methods
# -----------------------------------------------------
summary(cluster_summary(mat, clusters, method = "sum")) # total flow
summary(cluster_summary(mat, clusters, method = "mean")) # average
summary(cluster_summary(mat, clusters, method = "max")) # strongest
# -----------------------------------------------------
# Skip within-cluster computation for speed
# -----------------------------------------------------
cluster_summary(mat, clusters, compute_within = FALSE)
# -----------------------------------------------------
# Promote the layers to netobjects
# (as_tna() stores the aggregated weights as they are)
# -----------------------------------------------------
as_tna(cluster_summary(mat, clusters, method = "sum"))
Tabulate the temporal coefficients of an mlVAR fit
Description
coefs() returns the temporal coefficients of a build_mlvar() fit as a
data frame, one row per (outcome, predictor) pair: the fixed-effect
lagged regression coefficients that make up the temporal network, with
their standard errors and tests.
Only the within-person (temporal) coefficients are tabulated. The
between-subjects effects that enter the between-subjects network through
the D (I - Gamma) transformation are not given as a table of their own.
The p-values are not adjusted for the number of coefficients, and
significant is p < 0.05 for each coefficient on its own.
Usage
coefs(x, ...)
## S3 method for class 'net_mlvar'
coefs(x, ...)
## Default S3 method:
coefs(x, ...)
Arguments
x |
A fitted model; only a |
... |
Not used. |
Value
A data frame with one row per (outcome, predictor) pair and the
columns outcome (the variable predicted), predictor (the variable at
the earlier occasion), beta (the fixed-effect coefficient), se (its
standard error), t (beta / se), p (the two-sided p-value from the
normal distribution, 2 * pnorm(-abs(t)), which stays above zero for
large t), ci_lower and ci_upper (the 95% Wald interval,
beta plus or minus qnorm(0.975) standard errors) and significant
(p < 0.05).
Note
The idiographic package exports a function with the same
name. With both packages attached, the one attached last masks the
other; write Nestimate::coefs() to call this one.
Examples
# A three-variable ESM panel: 20 people x 20 beeps. `tired` is driven by
# `happy` one beep earlier, so the temporal network should recover it.
if (requireNamespace("lme4", quietly = TRUE)) {
set.seed(1)
n_beep <- 20
ar1 <- function(n, phi) as.numeric(stats::filter(stats::rnorm(n), phi,
method = "recursive"))
panel <- do.call(rbind, lapply(seq_len(20), function(i) {
happy <- ar1(n_beep, 0.4)
data.frame(
id = i,
beep = seq_len(n_beep),
happy = happy + stats::rnorm(1),
calm = ar1(n_beep, 0.3) + stats::rnorm(1),
tired = 0.5 * c(0, happy[-n_beep]) + stats::rnorm(n_beep) +
stats::rnorm(1)
)
}))
fit <- build_mlvar(panel, vars = c("happy", "calm", "tired"),
id = "id", beep = "beep")
fit
coefs(fit)
summary(fit)
}
Compare mixed Markov models across numbers of subgroups
Description
compare_mmm() fits a mixed Markov model with build_mmm() for each
number of subgroups in k and returns one row per fit with its
log-likelihood, information criteria (AIC, BIC, ICL), overall average
posterior probability (AvePP), entropy and convergence. Every fit uses
the same data and the same build_mmm() settings.
Lower AIC, BIC and ICL indicate more support relative to the other fits.
ICL adds a penalty for uncertain classification to BIC, so it favours
subgroups that separate cleanly (Biernacki, Celeux & Govaert, 2000);
AvePP and entropy describe that separation within each fit. The criteria
do not settle k on their own: check that every fit converged, that the
subgroups' transition matrices of the chosen fit differ in interpretable
ways (summary() of that fit prints them), and, when the criteria keep
falling at the largest k, extend the range.
Usage
compare_mmm(
data,
k = 2:5,
return_fits = FALSE,
n_starts = 50L,
max_iter = 200L,
tol = 1e-06,
smooth = 0.01,
seed = NULL,
covariates = NULL,
covariate_effect = c("em", "posthoc"),
estimator = c("auto", "firth", "multinom", "chisq")
)
## S3 method for class 'mmm_compare'
print(x, ...)
## S3 method for class 'mmm_compare'
summary(object, ...)
## S3 method for class 'mmm_compare'
plot(x, ...)
Arguments
data |
The sequences, in any form |
k |
The numbers of subgroups to fit, a non-empty vector of whole
numbers of at least 2; one model is fitted per value. Default |
return_fits |
Whether to keep the fitted models. With |
n_starts |
How many starting configurations to try, a positive whole
number. More starts make it likelier that the best local maximum is
found. Default |
max_iter |
The most EM iterations a start may run, a positive whole
number. Default |
tol |
The convergence tolerance: EM stops when the log-likelihood
changes by less than this between iterations (with |
smooth |
A pseudo-count added to every transition count before the
matrices are estimated, so a transition unseen in a subgroup gets a small
probability instead of zero. A finite non-negative number; default
|
seed |
A seed for reproducible starts, applied afresh to each fit
(every |
covariates |
Variables describing each sequence (such as a course or
a grade), given as a column name, a character vector of names, a
one-sided formula or a data frame, as in |
covariate_effect |
How |
estimator |
How the after-fit multinomial logit is estimated; it never
affects the EM. |
x |
For the |
... |
For the |
object |
For the |
Value
An mmm_compare object, a data frame with one row per value of
k. print() shows the table with a best
column marking the lowest BIC ("<-- BIC") and, when it falls on a
different row, the lowest ICL ("<-- ICL"), and returns that marked
table invisibly. summary() returns the same table as a plain data
frame with a best column holding "BIC", "ICL" or ""; when one
row has both minima it is marked "BIC" only. plot() draws BIC, AIC
and ICL against k, and returns the ggplot invisibly after printing
it. The table's columns are k, log_likelihood, AIC, BIC,
ICL, AvePP, Entropy and converged; return_fits = TRUE adds the
"fits" attribute.
References
Biernacki, C., Celeux, G., & Govaert, G. (2000). Assessing a mixture model for clustering with the integrated completed likelihood. IEEE Transactions on Pattern Analysis and Machine Intelligence, 22(7), 719–725. doi:10.1109/34.865189
See Also
Examples
seqs <- data.frame(V1 = sample(c("A","B","C"), 30, TRUE),
V2 = sample(c("A","B","C"), 30, TRUE))
comp <- compare_mmm(seqs, k = 2:3, n_starts = 1, max_iter = 10, seed = 1)
comp
seqs <- data.frame(
V1 = sample(LETTERS[1:3], 30, TRUE), V2 = sample(LETTERS[1:3], 30, TRUE),
V3 = sample(LETTERS[1:3], 30, TRUE), V4 = sample(LETTERS[1:3], 30, TRUE)
)
comp <- compare_mmm(seqs, k = 2:3, seed = 42)
print(comp)
# Retain the fits so the chosen model needs no re-run; summary() marks
# the minimum-BIC and minimum-ICL rows in its `best` column.
comp_with_fits <- compare_mmm(seqs, k = 2:3, seed = 42, return_fits = TRUE)
summary(comp_with_fits)
Compare two networks descriptively
Description
compare_model() compares two networks, or two weight matrices, edge by
edge and returns a battery of descriptive agreement measures: weight
deviations (mean, median, root-mean-square and maximum absolute
difference, relative mean absolute difference, coefficient-of-variation
ratio), four correlations (Pearson, Spearman, Kendall, distance
correlation), five dissimilarities (Euclidean, Manhattan, Canberra,
Bray-Curtis, Frobenius), five similarities (cosine, Jaccard, Dice,
overlap, RV coefficient) and two pattern agreements (rank and sign
agreement), with the two networks' metrics side by side and, on request,
their centrality differences. It takes two netobjects,
cograph_networks or square numeric matrices, or two members of a
netobject_group. Both weight matrices are scaled with the same
scaling before comparison, which decides how weights from different
estimators are put on a common footing.
The measures describe how alike the two estimated networks are; they say
nothing about whether a difference is larger than sampling variation
would produce. For that, test the difference with permutation() (two
transition networks) or with nct() on the two groups' observations
(psychological networks).
compare_networks() compares any number of networks with tidy tables
and a plot() that draws one view per call.
Usage
compare_model(x, ...)
## Default S3 method:
compare_model(x, ...)
## S3 method for class 'netobject'
compare_model(
x,
y,
scaling = "none",
measures = character(0),
network = TRUE,
...
)
## S3 method for class 'cograph_network'
compare_model(
x,
y,
scaling = "none",
measures = character(0),
network = TRUE,
...
)
## S3 method for class 'matrix'
compare_model(
x,
y,
scaling = "none",
measures = character(0),
network = TRUE,
...
)
## S3 method for class 'netobject_group'
compare_model(
x,
i = 1L,
j = 2L,
scaling = "none",
measures = character(0),
network = TRUE,
...
)
## S3 method for class 'net_comparison'
print(x, ...)
## S3 method for class 'net_comparison'
plot(
x,
type = c("scatter", "heatmap", "diff_hist", "weight_dist", "all"),
combined = TRUE,
...
)
Arguments
x |
The first network: a |
... |
Not used. |
y |
The second network, in the same forms (not used for a
|
scaling |
The scaling applied to each weight matrix before
comparison. Default
Scalings that produce negative weights ( |
measures |
Centrality measures to compare. Default |
network |
Whether to add the two networks' metrics side by side (the
metrics |
i, j |
For a |
type |
For |
combined |
For |
Details
The measures, scalings and edge metrics mirror tna::compare() (tna
1.5.4 and later) numerically. The distance correlation is that of
Szekely, Rizzo and Bakirov (2007), NA when one network is constant, and
the RV coefficient that of Robert and Escoufier (1976). A network's own
directed flag decides how its network metrics are computed; a plain
matrix has none, nor has a cograph_network without a directed field,
so an asymmetric one is read as directed and a
symmetric one as undirected, after its rows and columns are matched to
the other network's nodes by name. A tna model is read by the directed
flag of the network it is rebuilt into.
Value
A net_comparison object. Print it for the agreement measures,
the side-by-side network metrics and the centrality correlations;
plot() draws the edge-weight scatter or another view (see type).
The object is a list with:
- matrices
The two scaled weight matrices,
xandy, aligned by node.- difference_matrix
The scaled
xminus the scaledy.- edge_metrics
A data frame with one row per cell (
source,target, self-loops included): the two weights and their raw, absolute, squared, relative and rank differences, percentile difference, ratio (similarity_strength_index), relative change (difference_index), log ratio of 1 + weight (logarithmic_ratio,NAwhere a weight is -1 or below), standardised weights and their ratio. A ratio isNAwhere its denominator is zero, and the standardised weights areNAwhen a matrix is constant.- summary_metrics
A data frame of the 22 agreement measures, with columns
category,metricandvalue.- network_metrics
When
network = TRUE: a data frame with columnsmetric,xandy, one row per network metric.- centrality_differences, centrality_correlations
When
measuresis not empty (empty data frames when none of its names is valid): one row per node and measure (state,centrality,x,y,difference), and one row per measure with the correlation of the two networks' values.
print() returns its input invisibly.
plot() returns a ggplot; with type = "all", it draws the 2 x 2
grid and returns it invisibly as a gtable, or with combined = FALSE
returns the four ggplots invisibly as a named list.
References
Szekely, G. J., Rizzo, M. L., & Bakirov, N. K. (2007). Measuring and testing dependence by correlation of distances. The Annals of Statistics, 35(6), 2769–2794. doi:10.1214/009053607000000505
Robert, P., & Escoufier, Y. (1976). A unifying tool for linear multivariate statistical methods: The RV-coefficient. Journal of the Royal Statistical Society, Series C (Applied Statistics), 25(3), 257–265. doi:10.2307/2347233
Examples
nets <- build_network(group_regulation_long, method = "relative",
actor = "Actor", action = "Action", time = "Time",
group = "Achiever")
compare_model(nets)
Compare two or more networks
Description
compare_networks() compares two or more networks cell by cell, node by
node and on global metrics, and returns one net_network_comparison
object. It compares every pair of networks, or every network against one
reference, and takes any mix of netobjects, groups of them, tna
models and square weight matrices, as long as they share the same nodes in
the same order. Each table carries a pair column, so one call to a named
verb returns it for every pair. The comparison is descriptive by default;
test adds permutation, Bayesian and bootstrap evidence to the same
tables.
Every difference is diff = a - b, network a minus network b of a
pair, between two sets of point estimates. The similarity metrics
(Pearson, cosine, Jaccard and the others in the global table) describe
how alike the two weight matrices are; neither they nor a large diff
say whether a difference is larger than sampling variation would produce.
For that, rerun with test = "permutation" (or "bayes" for relative or
frequency networks) and read the sig column, and use adjust when many
edges are read at once. plot() draws one view of the comparison per call.
Usage
compare_networks(
...,
reference = NULL,
scaling = c("none", "minmax", "max", "rank", "zscore", "robust", "log", "log1p",
"softmax", "quantile", "frobenius", "row"),
measures = c("InStrength", "OutStrength", "Betweenness"),
labels = NULL,
test = "none",
iter = 1000L,
alpha = 0.05,
adjust = "none",
paired = FALSE,
rope = NULL,
seed = NULL,
actor = NULL
)
## S3 method for class 'net_network_comparison'
print(x, digits = 2L, ...)
## S3 method for class 'net_network_comparison'
plot(
x,
type = c("networks", "difference", "edges", "nodes", "global", "heatmap", "scatter",
"inference"),
pair = NULL,
combined = TRUE,
top_n = 20L,
measure = NULL,
labels = TRUE,
digits = 2L,
what = NULL,
...
)
Arguments
... |
The networks, two or more, in any mix of |
reference |
The network every other one is compared against, by name
or index; it is always |
scaling |
A rescaling applied to every weight matrix before the
comparison. |
measures |
The centrality measures compared in the node table.
Default |
labels |
Names for the networks, one per network after groups are
expanded; they replace the argument names. Default |
test |
The inference to add, one or more of |
iter |
The number of permutations, posterior draws or bootstrap
replicates per pair, at least 2. Default |
alpha |
The significance level of the permutation and bootstrap
tests, a number between 0 and 1; the Bayesian credible interval covers
|
adjust |
The multiplicity correction for the permutation p-values, any method of p.adjust(), applied within each pair and separately
to the edge and node tables, as |
paired |
Whether the networks hold paired observations, so the
permutation test swaps the two members of each pair instead of
shuffling all labels; the networks then need the same number of
sequences. It cannot be combined with |
rope |
The half-width of a region of practical equivalence on the
difference scale, for the Bayesian test. It adds |
seed |
An integer that makes the tests reproducible. It is passed
unchanged to the test of every pair, so |
actor |
The column identifying the actor each sequence belongs to
(such as |
x |
For the |
digits |
For the |
type |
For the |
pair |
For the |
combined |
For the |
top_n |
For the |
measure |
For the |
what |
Deprecated alias for |
Details
Cells. Every cell of the weight matrix is a row of the edge table,
the diagonal and the edges absent from one network (weight 0) included;
when both networks are undirected only the cells with from <= to are
kept. A difference smaller than sqrt(.Machine$double.eps) counts as no
difference (higher = "equal").
Guarding. Ratios are never Inf or NaN, and no pseudo-counts are
added: ratio is NA when weight_b is 0, rel_diff
(abs(diff) / (abs(a) + abs(b))) is NA when both weights are 0, and
log_ratio = log1p(a) - log1p(b) is NA when either weight is negative.
Inference. "permutation" runs permutation() per pair and adds
perm_effect, perm_p and perm_sig to the edge and node tables, and
two rows to the global table with permutation p-values: M, the sum of
the absolute differences over all cells, and S, the largest absolute
difference. With actor, whole actors are shuffled and the global table
also gains the rows "ICC", "Design effect (edges)" and
"Design effect (M)". "bayes" runs bayes_compare() per pair (prior
0.5, iter draws) and adds to the edge table bayes_diff (posterior
mean difference), bayes_ci_lower, bayes_ci_upper, bayes_pd
(probability of direction), bayes_p (2 * (1 - pd)) and bayes_sig;
with rope, also bayes_p_rope (a normal approximation from the
posterior mean and SD) and bayes_decision. "bootstrap" runs the
vertex bootstrap of vertex_compare() per pair and adds structural rows
(density, mean weight, centralization and, for directed networks,
reciprocity) to the global table,
with boot_observed_a, boot_observed_b, boot_se, boot_ci_lower,
boot_ci_upper, boot_z, boot_p and boot_sig. It reads only the
weights, so plain matrices support it; the other two tests need
build_network() output with data, or tna models, which are rebuilt
from their sequences when these reproduce the weights. The sig and
evidence columns take the permutation result when it was run (edge and
node tables), and otherwise the Bayesian one (edge table only).
Value
A net_network_comparison object. print() shows one line per
pair (Pearson correlation, mean and largest absolute difference, the
largest change) and returns x invisibly; summary() returns one row
per pair; the verbs of comparison_tables return the full tables; plot() draws one view per call. The
object's fields:
-
networks: the input networks asnetobjects, with scaled weights; -
matrices: the scaled weight matrices; -
pairs: one row per comparison, withpair,network_aandnetwork_b; -
edges: one row per pair and cell:pair,network_a,network_b,from,to,weight_a,weight_b,diff,abs_diff,rel_diff,ratio,log_ratio,rank_a,rank_b,rank_diff,percentile_diff,status(both,only_a,only_borneither),higher(the name of the higher network, orequal), and the inference columns; -
nodes: one row per pair, node and measure:pair,network_a,network_b,node,measure,value_a,value_b,diff,abs_diff,rank_a,rank_b,higher, and the inference columns;NULLwithoutmeasures; -
global: one row per pair and metric (22 descriptive metrics in five categories, and the inference rows):pair,network_a,network_b,category,metric,key,value, and the inference columns; -
network_metrics: one row per network and structural metric:network,metric,value; -
differences: onenetdifferenceobject per pair (fromsubtract_networks()); -
permutations: withtest = "permutation", thepermutation()result of each pair, named by pair; the settings
scaling,reference,measures,test,iter,alpha,adjust,paired,ropeandactor, withdirected(one logical per network),n_networksandn_pairs.
For the plot() method: a ggplot for the "edges", "nodes",
"global", "heatmap", "scatter" and "inference" views, or, with
combined = FALSE, a named list of them, one per pair, returned
invisibly. The "networks" and "difference" views draw in base
graphics (with cograph::splot() when cograph is installed, otherwise
with a built-in circular drawer that ignores ...) and return NULL
invisibly.
Errors
Every error that compare_networks() and its verbs raise has the class nestimate_compare_error, so one handler catches them all. The one met most often is nestimate_compare_node_mismatch, raised when the networks do not share the same nodes in the same order.
Plain argument-type checks raise unclassed errors, and errors from
permutation(), bayes_compare() and vertex_compare() keep their own
classes (for example nestimate_bad_actor for paired = TRUE with
actor).
An unknown name in measures is dropped with a nestimate_compare_warning.
Reading the figures
One colour contract holds in every view and every backend: "#4A6FE3"
marks network_a (the reference, when one is set) as the higher of the
two, "#D33F6A" marks network_b, and grey marks no difference; the
plotted quantity is always diff = a - b. Colour never carries the sign
alone: a solid line and a circular marker repeat "a higher", a dashed
line and a square marker repeat "b higher", and the printed value
carries its sign. When test was run, evidence is shown by opacity and a
starred (edge and node views; ** for p below 0.01, *** below 0.001,
as on the graph of permutation()) or annotated (inference view) label: a
non-significant difference is faded, never deleted.
See Also
compare_model() (two-network predecessor), permutation(),
bayes_compare(), vertex_compare(), subtract_networks().
Examples
# Regulation networks for the three courses, compared pairwise.
courses <- build_network(group_regulation_long, method = "relative",
actor = "Actor", action = "Action", time = "Time",
group = "Course")
cmp <- compare_networks(courses)
cmp
summary(cmp)
# `pair` takes the two network names, in either order.
edge_differences(cmp, pair = c("A", "B"))
global_differences(cmp, pair = c("A", "B"))
plot(cmp) # each network once
plot(cmp, type = "difference") # signed difference per pair
plot(cmp, type = "edges", pair = c("A", "B"))
# High against low achievers, with a permutation test on every edge.
achievers <- build_network(group_regulation_long, method = "relative",
actor = "Actor", action = "Action",
time = "Time", group = "Achiever")
cmp_perm <- compare_networks(achievers, test = "permutation",
iter = 20, seed = 1)
summary(cmp_perm)
plot(cmp_perm, type = "inference", top_n = 10)
Tabulate the results of a network comparison
Description
edge_differences() and its sibling verbs return the tables of a compare_networks() result:
-
summary(): one row per pair; -
edge_differences(): one row per pair and cell; -
node_differences(): one row per pair, node and measure; -
global_differences(): one row per pair and metric; -
network_metrics(): one row per network and structural metric.
Each is a data frame with no row names, numeric
columns rounded to digits decimals and p-value and
probability-of-direction columns left unrounded.
All but network_metrics() select pairs with the same pair argument as
the plot() method.
Usage
## S3 method for class 'net_network_comparison'
summary(object, pair = NULL, digits = 2L, ...)
edge_differences(x, pair = NULL, digits = 2L)
node_differences(x, pair = NULL, measure = NULL, digits = 2L)
global_differences(x, pair = NULL, digits = 2L)
network_metrics(x, digits = 2L)
## S3 method for class 'net_table'
print(x, digits = attr(x, "digits") %||% 2L, ...)
## S3 method for class 'net_table'
x[...]
Arguments
pair |
The comparisons to keep. Default |
digits |
The decimals kept in the numeric columns. Default |
... |
Ignored. For |
x, object |
A |
measure |
The centrality measures to keep in |
Value
Each verb returns a data frame of class net_table. Its print()
shows whole numbers without decimals, exact zeros as 0, other values
with digits decimals and p-values and probabilities of direction with
three decimals, and returns the table invisibly. The tables:
-
summary(): one row per pair, withpair,network_a,network_b,n_cells(cells compared),n_differing(cells whose weights differ),share_higher_a,share_higher_b,mean_abs_diff,max_abs_diff,pearson,spearman,cosine,jaccard,top_edge(the cell with the largest absolute difference) andtop_edge_higher; with the permutation or Bayesian test, alson_sig_edges, and with the permutation testn_sig_nodes(when there is a node table),m_stat,m_p,s_statands_p. -
edge_differences(): one row per pair and cell, withpair,network_a,network_b,from,to,weight_a,weight_b,diff,abs_diff,rel_diff,ratio,log_ratio,rank_a,rank_b,rank_diff,percentile_diff,status,higher, and the inference columns whentestwas used. -
node_differences(): one row per pair, node and measure, withpair,network_a,network_b,node,measure,value_a,value_b,diff,abs_diff,rank_a,rank_b,higher, and the inference columns. It raises an error of classnestimate_compare_no_nodeswhencompare_networks()was called withoutmeasures. -
global_differences(): one row per pair and metric, withpair,network_a,network_b,category,metric,key,value, and the inference rows and columns. -
network_metrics(): one row per network and structural metric, withnetwork,metricandvalue.
compare_networks() describes every column under Details and Value.
Examples
achievers <- build_network(group_regulation_long, method = "relative",
actor = "Actor", action = "Action",
time = "Time", group = "Achiever")
cmp <- compare_networks(achievers)
summary(cmp)
edge_differences(cmp)
edge_differences(cmp, digits = 4)
node_differences(cmp, measure = "InStrength")
global_differences(cmp)
network_metrics(cmp)
Compute cluster scores from a psychometric MCML fit
Description
composites() returns the per-observation cluster scores that the macro
network of a re-estimated build_mcml_pc() fit was estimated from: each
respondent's weighted, sign-corrected score on every cluster. These are
the scores to carry into a profile analysis, a regression or any other
model that needs one number per cluster per respondent.
A score is only as good as the items behind it: check the item weights
and misfit flags with item_loadings() and the stability of the weights
with loading_stability() before using the scores elsewhere.
Usage
composites(x, ...)
## S3 method for class 'mcml_pc'
composites(x, ...)
Arguments
x |
An |
... |
Ignored. |
Value
A data frame with one row per row of the input data, in input
order and with the input's row names, and one numeric column per
cluster, named by the cluster (as a syntactic name, so "Clu A" becomes
Clu.A). A row whose members of a cluster are all missing is NA in
that column; items missing only in part are averaged over the observed
ones. The macro network is estimated on the complete rows, so
build_network(composites(fit), method = ...) with the fit's estimator
reproduces it.
See Also
build_mcml_pc to create the fit,
item_loadings for the item weights behind these scores.
Examples
set.seed(1)
f <- stats::rnorm(200)
g <- stats::rnorm(200)
df <- data.frame(a1 = f + stats::rnorm(200), a2 = f + stats::rnorm(200),
a3 = f + stats::rnorm(200), b1 = g + stats::rnorm(200),
b2 = g + stats::rnorm(200), b3 = g + stats::rnorm(200))
clusters <- list(A = c("a1", "a2", "a3"), B = c("b1", "b2", "b3"))
fit <- build_mcml_pc(df, clusters, aggregation = "loadings",
method = "cor")
head(composites(fit))
Convert sequence data to counts, one-hot codes or transitions
Description
convert_sequence_format() turns wide or long sequence data into one of
four data frames: per-sequence state counts, per-sequence state presence
(one-hot), the list of consecutive transitions, or each event paired with
the one before it. It reads an event log (action set) or a wide table
(one row per sequence, one column per position). The counts can serve as
per-sequence behaviour profiles for the association estimators of
build_network() and for build_mcml_pc(). The id columns (those that
id_col names, and .rid for a wide table without id_col) are not
variables and must be set aside there (id_col in build_mcml_pc(),
actor in build_network()); the rid column is
dropped automatically.
Usage
convert_sequence_format(
data,
seq_cols = NULL,
id_col = NULL,
action = NULL,
time = NULL,
format = c("frequency", "onehot", "edgelist", "follows")
)
Arguments
data |
A data frame of sequences: an event log or a wide table. |
seq_cols |
The state columns of a wide table; setting them declares
a wide table. Default |
id_col |
The identifier column(s), copied to every output row. In an
event log, each unique combination of their values is one sequence,
and it is required: an event log without |
action |
The column holding each event's state; setting it declares
an event log. Default |
time |
The column that orders the events within each sequence of an
event log; without it, events keep their row order. A wide table leaves
it out of the state columns. Default |
format |
The output format: |
Details
A missing state (NA or an empty string) is dropped and the states on
either side are joined, so a sequence A, NA, B gives the transition
A -> B. frequencies() counts no transition across a missing state
instead.
Value
A data frame with the id column(s) first. For "frequency" and
"onehot": one row per sequence, a rid column identifying the
sequence, and one integer column per state, holding counts or 0/1. For
"edgelist": one row per transition, with columns from and to. For
"follows": one row per event after the first of its sequence, with
columns act and follows. An event log's rows come out sorted by
id_col.
See Also
frequencies for building transition frequency matrices.
Examples
# Wide format input
seqs <- data.frame(V1 = c("A","B","A"), V2 = c("B","A","C"), V3 = c("A","C","B"))
convert_sequence_format(seqs, format = "frequency")
convert_sequence_format(seqs, format = "edgelist")
Build a co-occurrence network of items in transactions
Description
cooccurrence() builds an undirected network of items that appear
together in the same transaction (a document, a session, a record): an
edge joins two items that occur together, weighted by how often they do,
or by a similarity measure that adjusts that count for how often each item
occurs overall. With similarity = "relative" the network is directed. It reads delimited columns (keywords separated by ";"),
a long table of items per transaction, a 0/1 incidence table, wide
sequences or a list of transactions; the Details say how each is
recognised.
Raw counts grow with how frequent the two items are, so the most frequent
items dominate a count network. The similarity measures correct for that
in different ways (van Eck & Waltman, 2009); compare a few before reading
which pairs are strongest. The network is descriptive: it keeps no source
data, so bootstrap_network() and permutation() cannot resample it.
Usage
cooccurrence(
data,
field = NULL,
by = NULL,
sep = NULL,
similarity = c("none", "jaccard", "cosine", "inclusion", "association", "dice",
"equivalence", "relative"),
threshold = 0,
min_occur = 1L,
diagonal = TRUE,
top_n = NULL,
...,
format = c("auto", "binary")
)
Arguments
data |
The transactions, in one of these forms:
A network object ( |
field |
The column holding the items, which become the nodes. With
|
by |
The column that defines the transactions of a long table: each
of its values is one transaction, holding the distinct |
sep |
The separator that splits delimited |
similarity |
How the co-occurrence count
A zero denominator is replaced by 1, so an item without co-occurrences
gets weight 0 rather than |
threshold |
The smallest weight kept: weights below it, on the scale
of |
min_occur |
The fewest transactions an item must appear in to be
kept. Rarer items are dropped before the co-occurrences are counted, and
transactions left empty are dropped with them. Default |
diagonal |
Whether the diagonal is kept. With |
top_n |
How many of the strongest off-diagonal edges to keep: pairs
in an undirected network, directed cells with |
... |
Not used; an argument given here is ignored with a warning. |
format |
How 0/1 columns are read. Columns of only 0 and 1 (or
|
Details
Six input forms are recognised from data and from which of field,
by and sep are set:
-
Delimited:
field(one column) andsep. Each cell is split bysep, trimmed, and its distinct values form a transaction. -
Multi-column delimited:
field(several columns) andsep. The split values of a row's columns are pooled into one transaction. -
Long bipartite:
fieldandby. The distinctfieldvalues within eachbygroup form a transaction. -
Binary: none of the three, all values 0/1 or logical, and
format = "binary". Columns are items, rows are transactions; a missing cell is no occurrence. Withoutformat = "binary"such data is refused, since 0/1 columns could also be recoded positions. -
Wide sequence: none of the three, other values. The distinct states of each row form a transaction, leaving out missing values and the void markers (
"%","*","","NA","NaN"). A data frame must be a single column or a numbered run of position columns (T1,T2, ...) with nothing beside it; any other frame raises an error of classnestimate_bad_input, and a column calledactionand repeated column names are refused the same way. -
List: a plain list of character vectors.
To count co-occurrence of states within sequences through
build_network(), with its resampling verbs, use
build_network(method = "co_occurrence") or build_cna() instead.
All forms are turned into a list of transactions, which min_occur
filters. The raw counts are crossprod(B) of the binary transaction
matrix B; similarity is applied to them, then threshold, then
top_n.
Value
A netobject (class c("netobject", "cograph_network")),
undirected (directed with similarity = "relative"), with
method = "co_occurrence_fn". Print it for an
overview; extract_edges() gives one row per edge,
extract_transition_matrix() the weight matrix (one row and column per
item kept), net_centrality() the node centralities, and
cograph::splot() draws it. It is built without build_network() and
holds no source data (data is NULL). Its params record
similarity, threshold, min_occur, diagonal, top_n,
n_transactions and n_items.
References
van Eck, N. J., & Waltman, L. (2009). How to normalize co-occurrence data? An analysis of some well-known similarity measures. Journal of the American Society for Information Science and Technology, 60(8), 1635–1651.
See Also
build_cna for sequence-positional co-occurrence via
build_network().
Examples
# Delimited field (e.g., keyword co-occurrence)
df <- data.frame(
id = 1:4,
keywords = c("network; graph", "graph; matrix; network",
"matrix; algebra", "network; algebra; graph")
)
net <- cooccurrence(df, field = "keywords", sep = ";")
# Long/bipartite
long_df <- data.frame(
paper = c(1, 1, 1, 2, 2, 3, 3),
keyword = c("network", "graph", "matrix", "graph", "algebra",
"network", "algebra")
)
net <- cooccurrence(long_df, field = "keyword", by = "paper")
# List of transactions
transactions <- list(c("A", "B"), c("B", "C"), c("A", "B", "C"))
net <- cooccurrence(transactions, similarity = "jaccard")
# Binary matrix
bin <- matrix(c(1,0,1, 1,1,0, 0,1,1), nrow = 3, byrow = TRUE,
dimnames = list(NULL, c("X", "Y", "Z")))
net <- cooccurrence(bin, format = "binary")
Simulated learning actions over seven days
Description
daily_actions is a simulated log of the learning actions of 30 students
over seven days: plan, read, write, discuss and review. Each
student has between 51 and 98 actions, spread unevenly over the days: a
student acts at least once and at most 41 times on one day (median 9), and
a student's busiest day has between 2 and 31 times as many actions as the
quietest. Each student favours some actions over others; the most
frequent action of a student accounts for 32% to 78% of their actions. The
rows of each student are in time order. The data suit sequence plots and
networks in which every actor has a different number of actions per
period, as in sequence_plot(periods = "day").
Usage
daily_actions
Format
A data frame with 2,280 rows and 3 character columns:
- student
Student identifier,
"s01"to"s30".- day
The day of the action,
"day 1"to"day 7".- action
The learning action:
plan,read,write,discussorreview.
Source
Simulated with the script data-raw/daily_actions.R (seed 2026).
Examples
sequence_plot(daily_actions, actor = "student", action = "action",
periods = "day")
Draw a state distribution plot
Description
distribution_plot() draws how the states are distributed at each time
point: for every position column it counts the sequences in each state
and stacks the shares (or counts) as areas (default) or bars. It takes the
same inputs as sequence_plot() (wide sequences, networks built from
sequences, clusterings, mixture fits and tna models), draws one panel
per group or cluster, and is the figure sequence_plot(type = "distribution") draws.
The plot shows the composition of the sample at each time point, not how
individual sequences move: the same bands can come from sequences that
stay in one state or from sequences that change state at every step. Look
at single sequences with sequence_plot() and at the transitions with
build_tna(). Missing cells form their own band by default (na), so
sequences that end early stay visible instead of inflating the other
shares.
Usage
distribution_plot(
x,
group = NULL,
scale = c("proportion", "count"),
geom = c("area", "bar"),
na = TRUE,
trim = NULL,
trim_clusterwise = FALSE,
state_colors = NULL,
na_color = "grey90",
frame = FALSE,
width = NULL,
height = NULL,
main = NULL,
show_n = TRUE,
time_label = "Time",
xlab = NULL,
y_label = NULL,
ylab = NULL,
tick = NULL,
ncol = NULL,
nrow = NULL,
combined = TRUE,
legend = c("right", "bottom", "none"),
legend_size = NULL,
legend_title = NULL,
legend_ncol = NULL,
legend_border = NA,
legend_bty = "n",
cols = NULL
)
Arguments
x |
The sequences: a wide data frame or matrix (one row per
sequence, one column per time point), a |
group |
A vector of one group label per sequence (length
|
scale |
What the y-axis shows: |
geom |
How the bands are drawn: |
na |
Whether missing cells are drawn as an extra band coloured
|
trim |
Cuts the time axis (one number) or the time axis and the
rows (two numbers); |
trim_clusterwise |
For grouped plots with a fractional |
state_colors |
Colours for the state bands: an unnamed vector, one
colour per state in sorted state order, or a named vector such as
|
na_color |
The colour of the missing-cell band. Default |
frame |
Whether to draw a box around each panel, and axis lines.
Default |
width, height |
Size of a new graphics device, in inches, opened
only in an interactive session (the other dimension defaults to 7).
Default |
main |
The plot title. With several panels on one figure it is
drawn above them; with several panels and |
show_n |
Whether to add the number of sequences, |
time_label |
The x-axis label. Default |
xlab |
Another name for |
y_label |
The y-axis label. Default |
ylab |
Another name for |
tick |
Label every |
ncol, nrow |
The panel grid. Default |
combined |
Whether to draw all panels on one figure. |
legend |
Where the legend goes: |
legend_size |
The legend text size. Default |
legend_title |
A title for the legend. Default |
legend_ncol |
The number of legend columns. Default |
legend_border |
The colour of the swatch borders. Default |
legend_bty |
The legend box: |
cols |
For a wide data frame: the columns holding the time points.
Needed when they are not a numbered run ( |
Value
Invisibly, a list describing the drawn figure:
- counts
A named list, one entry per panel, each a state by time point matrix of counts; rows are named by
levels, columns are the time points kept.- proportions
The same matrices with each column divided by its total (an empty time point stays 0).
- levels
The state labels in plotting order, with
"NA"appended whenna = TRUE.- palette
The fill colours, one per entry of
levels.- groups
The panel labels (
"all"when ungrouped), in the order ofcountsandproportions.
See Also
Examples
distribution_plot(as.data.frame(trajectories))
Tabulate the effects of an outcome model
Description
effects_table() returns the effect table of an outcome_model() fit:
one row per term, with its estimate, confidence interval and corrected
p-value, rounded for reading. Arguments keep the intercept or only the
significant terms.
Usage
effects_table(
x,
intercept = FALSE,
significant = FALSE,
alpha = 0.05,
digits = 3
)
Arguments
x |
An |
intercept |
Whether to keep the intercept row. Default |
significant |
Whether to keep only the terms whose corrected p-value
( |
alpha |
The threshold for |
digits |
The decimal places of the numeric columns. Default |
Value
A data frame with the columns of the model's effect table (term,
estimate, std_error, statistic, ci_lower, ci_upper, p_value,
p_adj, and for a binomial fit odds_ratio, or_lower and
or_upper), one row per retained term. The intercept row is dropped
unless intercept = TRUE, and every term is kept unless
significant = TRUE restricts them to p_adj < alpha.
Examples
set.seed(1)
d <- data.frame(hint = rbinom(200, 1, 0.5))
d$success <- rbinom(200, 1, plogis(-0.3 + 0.9 * d$hint))
effects_table(outcome_model(d, outcome = "success", predictors = "hint"))
Estimate transition entropy with Bayesian credible intervals
Description
entropy_bayes() puts credible intervals on the entropy quantities of
transition_entropy() and on the edge-level decomposition of
entropy_network(). Each row of the transition count matrix gets an
independent Dirichlet posterior (counts + prior), and Monte Carlo draws
from it carry the uncertainty of the counts into the entropy rate, the
stationary entropy, the redundancy, each state's branching entropy and
stationary probability, and every edge's entropy contribution. Each is
reported as a posterior mean with an equal-tailed credible interval. The
counts are recovered from a network, a tna model, a count matrix or
sequence data (see x); a netobject_group or a group_tna gives one
result per group.
The practical purpose is to exclude unstable estimates: an edge
whose contribution rests on a handful of observations has a wide
posterior, and it is flagged as not credible unless it credibly accounts
for at least min_share of the entropy rate. The pruned network keeps the
credible edges only, the stable entropy skeleton. The posterior treats
every transition as an independent draw from its row of a first-order
chain; whether a first-order chain describes the sequences is a separate
question, which markov_order_test() tests.
Usage
entropy_bayes(
x,
prior = 0.5,
draws = 4000,
ci = 0.95,
min_share = 0.01,
base = 2,
seed = NULL
)
## S3 method for class 'net_entropy_bayes'
print(x, digits = 3, ...)
## S3 method for class 'net_entropy_bayes_group'
print(x, ...)
## S3 method for class 'net_entropy_bayes_group'
summary(object, ...)
## S3 method for class 'net_entropy_bayes_group'
plot(x, top = 25, title = paste("Bayesian edge entropy", "contributions"), ...)
## S3 method for class 'net_entropy_bayes'
summary(object, ...)
## S3 method for class 'net_entropy_bayes'
plot(x, top = 25, title = "Bayesian edge entropy contributions", ...)
Arguments
x |
The transition counts: a frequency |
prior |
The Dirichlet concentration added to every cell of the count
matrix, a positive number. Default |
draws |
The number of Monte Carlo posterior draws, at least 100.
Default |
ci |
The mass of the credible intervals, between 0 and 1. Default
|
min_share |
The credibility threshold, a proportion in |
base |
The logarithm base, which sets the unit: |
seed |
An integer that makes the draws reproducible. Default |
digits |
For |
... |
For the |
object |
For |
top |
For |
title |
For |
Details
With prior > 0 the posterior puts mass on every transition, so the
contribution draws are strictly positive and a rule such as "the interval
excludes zero" would flag every edge as credible. The share criterion is
used instead: an edge is stable when it credibly carries at least
min_share of h(P). An unobserved transition (count 0) gets prior
mass only; it is left out of the edge table and of both networks.
The posterior mean entropy rate differs from the plug-in estimate of
transition_entropy() in two opposite ways: the prior pulls every row
toward uniform, which raises the entropy, and averaging over the posterior
lowers it. Which effect wins depends on the data (on the first 200 events of
group_regulation_long the posterior mean is above the plug-in value); the
difference is largest on sparse counts and vanishes as the counts grow.
Value
A net_entropy_bayes object, or for a netobject_group (or a
group_tna) a net_entropy_bayes_group: a named list of them, one per group.
print() shows the posterior mean and credible interval of the entropy
rate, stationary entropy and redundancy, and how many edges are
credible; for a group, each group's entropy rate. For a group,
summary() returns the chain-level table of every group stacked, with a
group column, and plot() draws the forest plot below in one panel
per group. For one network, summary() prints the
chain-level table and the per-edge table and returns the per-edge data
frame invisibly. plot() returns a ggplot forest plot of the edges
with the largest posterior mean contributions: the mean and credible
interval of each, credible edges in Okabe-Ito blue and unstable ones in
grey, with a dashed line at min_share of the posterior mean entropy
rate, the stability criterion. The print() methods return their input
invisibly. The object's fields:
- summary
Data frame, one row per chain-level quantity (
entropy_rate,stationary_entropy,redundancy), with the posteriormean,sd,ci_lowerandci_upper.- states
Data frame, one row per state: the posterior mean, sd and credible interval of its branching entropy, and the posterior mean and credible interval of its stationary probability.
- edges
Data frame, one row per observed transition (
from,to,count), sorted by contribution, largest first: the posterior mean, sd and credible interval of its contribution (inbaseunits), the posterior mean and credible interval of its share of the entropy rate (a proportion), and thecredibleflag.- network
A
netobject: the posterior-mean entropy network, every observed edge included, with the entropy edge style (vermilion edges, 2-digit labels, no minimum-weight pruning, node rings showing the posterior mean stationary distribution).- model
A
netobject: the pruned entropy network, posterior means wherecredibleand0elsewhere, styled the same way.- draws_entropy_rate
The posterior draws of the entropy rate, for further analysis or plotting.
- prior, draws, ci, min_share, base
The settings used.
- states_names
Character vector of state names.
References
Cover, T.M. & Thomas, J.A. (2006). Elements of Information Theory, 2nd ed. Wiley.
See Also
transition_entropy, entropy_network,
bayes_compare
Examples
net <- build_network(group_regulation_long, method = "relative",
actor = "Actor", action = "Action", time = "Time")
eb <- entropy_bayes(net, draws = 200, seed = 1)
eb
summary(eb)
plot(eb)
Decompose the entropy rate into a network of transitions
Description
entropy_network() splits a chain's entropy rate into one term per
transition and returns the terms as a network. The entropy rate
h(P) = -\sum_{ij} \pi_i P_{ij} \log_b P_{ij}
(transition_entropy(); Krejtz et al., 2015, 2025) is a sum over
transitions, so every edge i \to j owns the exact term
\pi_i P_{ij} \log_b(1/P_{ij}) of the chain-level uncertainty. No new
quantity is estimated: the network places the summands of the
entropy-rate equation on the transition graph, which shows where in the
process the uncertainty lies. Two other edge weights are available: each
transition's surprisal, and its contribution to the entropy production
rate (irreversibility). The result is a regular netobject, so it prints,
summarises and plots (cograph::splot()) like any other Nestimate
network.
Under the default weight, a heavy edge is a transition that is both
frequent and unpredictable; under "surprisal", a heavy edge is a rare
one, whatever its frequency. The weights are computed from one estimated
transition matrix, so an edge that rests on a few observations can carry a
large weight by chance: entropy_bayes() gives each contribution a
credible interval and keeps only the edges that credibly hold a share of
the entropy rate.
Usage
entropy_network(
x,
base = 2,
weight = c("contribution", "surprisal", "production"),
scaling = c("none", "share", "chance"),
normalize = TRUE
)
Arguments
x |
The chain: a |
base |
The logarithm base, which sets the unit: |
weight |
What each edge's weight measures:
|
scaling |
How the weights are expressed. |
normalize |
Whether rows that do not sum to 1 (a frequency network, a
count matrix) are divided by their sums, with a warning. With |
Details
An impossible transition (P_{ij} = 0) gets weight 0 under every
definition (the 0 \log 0 = 0 convention), so the entropy network has
no edge the transition network lacks. Self-loops are kept like any other
edge; their production weight is always 0. A deterministic transition
(P_{ij} = 1) also gets contribution and surprisal 0: observing the
inevitable carries no information.
Value
A netobject (class c("netobject", "cograph_network"), also
for a bare cograph_network input) with
method "entropy", whose weights are the per-edge entropy quantities.
Print it for an overview; summary() (see build_network()) gives its
network metrics,
extract_edges() one row per edge, and cograph::splot() draws it.
When x is a network (or sequence data, from which a relative network
is built), the result is that network with the entropy weights swapped
in: its initial probabilities, metadata, node groups and node
coordinates are kept, so it plots with the same TNA styling and layout
as its source. A bare cograph_network is first converted to a
netobject, which keeps its nodes, data, metadata, node groups and
parameters but no other field (its inits, for one, is dropped). The
stored parameters are base, weight, scaling,
the entropy rate entropy_rate (whatever the weight) and the stationary
distribution stationary, plus production_rate and n_oneway_pairs
when weight = "production".
The object also declares the entropy house style through its
meta$splot producer contract (honoured by cograph >= 2.4.4): no
minimum-weight pruning (bit values are smaller than probabilities), edge
labels with 2 digits (1 for "share"), vermilion edges, node rings
showing the stationary distribution, and TNA rather than psychometric
geometry. The production weights are signed, so they keep cograph's
positive and negative edge colours instead of the vermilion. With
weight = "surprisal" and scaling = "chance", the edges are drawn and
sized by the transition probabilities, transitions likelier than chance
in blues (darker for likelier) and those at or below chance dashed grey.
Because the contract states the styling outright, cograph needs no
knowledge of the "entropy" method: cograph::splot(ent) renders it
with no arguments, and any argument given overrides the contract.
References
Cover, T.M. & Thomas, J.A. (2006). Elements of Information Theory, 2nd ed., chapter 4. Wiley.
Krejtz, K., Duchowski, A., Szmidt, T., Krejtz, I., Gonzalez Perilli, F., Pires, A., Vilaro, A., & Villalobos, N. (2015). Gaze transition entropy. ACM Transactions on Applied Perception, 13(1), 4:1-4:20. doi:10.1145/2834121
Krejtz, K., Hughes, C.J., Stasiak, I., Duchowski, A., & Krejtz, I. (2025). Real-time mobile transition matrix entropy based on eye and head movements. Proceedings of ETRA '25. doi:10.1145/3715669.3723128
See Also
transition_entropy for the chain- and state-level
summary, entropy_bayes for credible intervals on the
decomposition, build_network.
Examples
net <- build_network(group_regulation_long,
method = "relative",
actor = "Actor", action = "Action", time = "Time")
ent <- entropy_network(net)
ent
if (requireNamespace("cograph", quietly = TRUE)) {
cograph::splot(ent)
}
Track transition entropy over time in sliding windows
Description
entropy_trajectory() tracks transition entropy over time: it forms the
transitions within each actor's sequence of an event log, pools them in
time order, and slides a window of a fixed number of transitions across
the stream, giving one entropy estimate per window. A group column gives
one trajectory per group. This turns transition entropy from a snapshot
into a process measure, as Krejtz et al. (2025) do when they track gaze
transition entropy through the phases of a task.
A falling trajectory means the transitions become more predictable
(routinisation), a rising one less predictable (exploration), and a level
shift marks a change of phase. Each window's estimate rests on window
transitions, and with the default step neighbouring windows share four
fifths of them, so their estimates are not independent: read the smoothed trend of plot() rather
than single windows. For the whole-process value with credible intervals,
use transition_entropy() and entropy_bayes().
Usage
entropy_trajectory(
data,
action = NULL,
actor = NULL,
time = NULL,
group = NULL,
window = 500L,
step = NULL,
base = 2
)
## S3 method for class 'net_entropy_trajectory'
print(x, digits = 3, ...)
## S3 method for class 'net_entropy_trajectory'
summary(object, ...)
## S3 method for class 'net_entropy_trajectory'
plot(
x,
normalized = FALSE,
span = 0.4,
title = "Transition entropy over time",
iter = 200L,
ci_level = 0.95,
seed = NULL,
...
)
Arguments
data |
An event log (a data frame with one row per event, read with
|
action |
The column of an event log holding each event's state.
Default |
actor |
The column identifying sequences: transitions are formed only
between consecutive events of the same actor (within the same group).
Default |
time |
The timestamp column, which orders the events within each
actor and places the windows on a time axis. Default |
group |
A column splitting the data into parallel trajectories (for
example a condition or an achievement level), each with its own windows.
Default |
window |
The number of transitions per window, at least 10. Default
|
step |
The number of transitions between the starts of consecutive
windows. Default |
base |
The logarithm base, which sets the unit: |
x |
For the |
digits |
For |
... |
For the |
object |
For |
normalized |
For |
span |
For |
title |
For |
iter |
For |
ci_level |
For |
seed |
For |
Details
Each window's entropy is the empirical conditional entropy
-\sum_{ij} (n_{ij}/N) \log_b(n_{ij}/n_{i\cdot}), which weights rows
by their observed occupancy rather than by the stationary distribution
from the eigenvector. Within a short window the chain is often not ergodic
(absorbing fragments, unvisited states), where that eigenvector is
undefined or misleading; the empirical estimator is the standard windowed
choice and converges to the stationary entropy rate over long stationary
stretches.
The transitions of all actors are pooled in time order within each group
(ties broken by actor, then by input order). A window shorter than
window at the end of a stream is dropped; a group whose stream is
shorter than window gets one window covering all of it, with a warning.
Fewer than two transitions in all raise an error.
The band of plot() is a bootstrap over actors (Davison & Hinkley, 1997):
each resample draws a group's actors with replacement, rebuilds its
windows from their transitions in time order and fits the same loess
trend. The band is the basic bootstrap interval of the trend at each
time: the central ci_level of the resampled trends, reflected about the
observed trend. It takes the spread of the resampled trends around the
observed one as the spread of the observed trend around the true one, so
a systematic shift of the resamples is carried to the other side of the
trend rather than kept. The plug-in entropy of a window is biased
downward (Miller, 1955), by about (c - r) / (2N \ln b) for
c observed transition types from r states in N
transitions, and resampled actors (repeated transitions) shift it
further down, so percentile limits tend to sit below the trend. In a
simulation (40 datasets of 100 actors with 20 steps of a stationary
4-state chain, window = 300, step = 100) the 95% band covered the
true entropy rate at mid-study in 38 of the 40, missing once on each
side. Whole actors are resampled
because the windows overlap (each transition sits in about
window / step of them) and an actor's
transitions depend on each other, so a band from the loess standard
error, which treats the windows as independent, would be too narrow.
A resample whose trend cannot be fitted (too few windows, or a loess
warning) is left out of the band, and the plot warns how many were, with
class nestimate_dropped_resamples; a time reached by fewer than half of
the iter resamples has no band. A group with one actor has no band
(warning class nestimate_single_actor_band).
Value
A net_entropy_trajectory object. print() shows each group's
number of windows and its mean and range of entropy, and returns its
input invisibly. summary() returns a data frame with one row per
group: group, windows, the mean, sd, min and max of the
window entropies, the entropy of the first and last windows, and
their difference change (negative when the transitions became more
predictable). plot() returns a ggplot with a loess-smoothed trend
per group and its bootstrap confidence band, each group in an Okabe-Ito
colour that no state uses and named at the end of its trend; more groups
than those colours are drawn one panel each. The object's fields:
- trajectory
Data frame, one row per window:
group,window(index within the group),time(the window's midpoint; a row number when there is notimecolumn),time_startandtime_end(the time, or row number, of the window's first and last transition),n_transitions,n_states(distinct states in the window),entropy(inbaseunits per transition) andentropy_norm(divided by\log_bof the window's number of states, floored at 2 states so the ceiling is never zero; in[0, 1]).- window, step, base
The settings used.
- states
The states of the whole log.
- stream
The transitions in time order within each group (state codes, time, group and actor), from which
plot()resamples.- state_palette
The colours of the states (the input network's own, or Okabe-Ito dealt over the sorted states).
plot()draws the groups in the Okabe-Ito colours these leave, so a group never takes a state's colour.
References
Krejtz, K., Hughes, C.J., Stasiak, I., Duchowski, A., & Krejtz, I. (2025). Real-Time Mobile Transition Matrix Entropy Based on Eye and Head Movements. ETRA '25. doi:10.1145/3715669.3723128
Cover, T.M. & Thomas, J.A. (2006). Elements of Information Theory, 2nd ed. Wiley.
Davison, A.C. & Hinkley, D.V. (1997). Bootstrap Methods and Their Application. Cambridge University Press.
Miller, G.A. (1955). Note on the bias of information estimates. In H. Quastler (Ed.), Information Theory in Psychology (pp. 95–100). Free Press.
See Also
transition_entropy for the whole-process snapshot,
entropy_bayes for credible intervals on it.
Examples
tr <- entropy_trajectory(group_regulation_long,
action = "Action", actor = "Actor",
time = "Time", group = "Achiever")
tr
summary(tr)
plot(tr)
# sequences: the network of the engagement trajectories, by course
net <- build_network(trajectories, method = "relative")
entropy_trajectory(net, window = 300, step = 50)
Estimate a network (deprecated)
Description
estimate_network() is deprecated: use build_network() instead. It
passes its arguments to build_network() unchanged and returns what that
returns, after a warning of class deprecatedWarning.
Usage
estimate_network(
data,
method = "relative",
params = list(),
scaling = NULL,
threshold = 0,
level = NULL,
...
)
Arguments
data |
The data, as for |
method |
The estimator, as in |
params |
Settings for the estimator, as a named list, as on the
method's page (for example |
scaling, threshold |
As in |
level |
Multilevel decomposition for the association methods, as in
|
... |
Further arguments for |
Value
A netobject, exactly as build_network() returns it (a
netobject_group or netobject_ml when ... or level asks for one).
See Also
Examples
data <- data.frame(T1 = c("x","y","z","x"), T2 = c("y","x","z","y"))
net <- estimate_network(data, method = "relative")
Compute the Euler characteristic of a simplicial complex
Description
euler_characteristic() returns the Euler characteristic of a simplicial
complex, \chi = \sum_{k=0}^{d} (-1)^k f_k, where f_k is the
number of k-simplices and d the dimension of the complex. By the
Euler-Poincare theorem it also equals \sum_{k} (-1)^k \beta_k, the
alternating sum of the betti_numbers().
Usage
euler_characteristic(sc)
Arguments
sc |
A |
Value
A single integer.
Examples
mat <- matrix(c(0,.6,.5,.6,0,.4,.5,.4,0), 3, 3)
colnames(mat) <- rownames(mat) <- c("A","B","C")
sc <- build_simplicial(mat, threshold = 0.3)
euler_characteristic(sc)
Evaluate link predictions against known edges
Description
evaluate_links() measures how well each index of a predict_links()
result recovers a set of known edges. For each index it returns the area
under the ROC curve (AUC), the average precision, and the precision among
the top k predictions.
The AUC is the probability that a known edge scores higher than a pair
that is not one (ties count half), so 0.5 is chance level. Average
precision is the mean of the precisions at the rank of each known edge,
and precision@k the share of known edges among the k
highest-scoring pairs. Pairs with the same score are not ordered: average
precision is taken over the distinct scores (as scikit-learn's
average_precision_score), and a group of tied pairs across the k-th
place counts by the share of its places within the top k. Only the pairs listed in the predictions are
evaluated: with exclude_existing = TRUE, the default of
predict_links(), the network's current edges are not scored, so the
known edges should be ones held out of the network (a later period, a
removed subset), and top_n limits the evaluation to the pairs it kept.
The AUC is NA when the evaluated pairs include no known edge, or
nothing but known edges.
Usage
evaluate_links(pred, true_edges, k = c(5L, 10L, 20L))
Arguments
pred |
A |
true_edges |
The known edges: a data frame with columns |
k |
The cut-offs for precision |
Value
A data frame with one row per index: method, auc,
average_precision (0 when no evaluated pair is a known edge), and
one precision_at_<k> column per value of k. A prediction with no
listed pairs (every possible link already exists) gives a zero-row
data frame with these columns.
Examples
seqs <- data.frame(
V1 = c("A", "B", "C", "D", "A", "C", "E", "B"),
V2 = c("B", "C", "D", "E", "C", "E", "A", "D"),
V3 = c("C", "D", "E", "A", "D", "A", "B", "E")
)
net <- build_network(seqs, method = "relative")
pred <- predict_links(net, exclude_existing = FALSE)
# Evaluate against the network's own edges as the known truth
evaluate_links(pred, extract_edges(net, threshold = 0.001))
Extract the edge list of a network
Description
extract_edges() returns the edges of a network as a data frame, one row
per edge with its weight, read from the weight matrix (rows are the
from states, columns the to states). It reads every input
extract_transition_matrix() reads; an mcml gives one edge list per
layer.
An edge is a cell whose absolute weight is above threshold, so with
the default threshold = 0 every non-zero cell is an edge, negative
weights (in correlation, partial-correlation and mlVAR networks)
included, and zero cells are not. A directed network lists every
ordered pair; an undirected one lists each edge once, with from the
earlier state in the matrix order. A network's own directed field
decides which; a tna model is directed unless it is a co-occurrence
model, and a bare matrix is undirected when it is symmetric.
Usage
extract_edges(model, threshold = 0, include_self = FALSE, sort_by = "weight")
Arguments
model |
The network: a |
threshold |
Cells whose absolute weight is at most |
include_self |
Whether to keep self-loops (a state followed by
itself), |
sort_by |
The row order: |
Details
An edge list is the form most other network tools (igraph, export to Gephi or a spreadsheet) take.
Value
For a single network: a data frame with one row per edge and the columns:
- from
The source state.
- to
The target state.
- weight
The edge weight (for a
"relative"network, the transition probability).- n_replies
For a
"latency"network only: the number of replies the edge holds (an integer).- median_latency
For a
"latency"network only: the median time of those replies, in seconds.
For a group of networks (netobject_group): one such data frame with
a group column first, one row per network and edge, the networks in
their order and each sorted by sort_by.
For an mcml: a named list of such data frames, macro first and then
one per cluster.
Note
The idiographic package exports a function with the same
name. With both packages attached, the one attached last masks the
other; write Nestimate::extract_edges() to call this one.
See Also
extract_transition_matrix for the full matrix,
build_network for network estimation.
Examples
seqs <- data.frame(V1 = c("A","B","A"), V2 = c("B","A","C"), V3 = c("A","C","B"))
net <- build_network(seqs, method = "relative")
edges <- extract_edges(net, threshold = 0.05)
head(edges)
Extract the initial-state probabilities of a network
Description
extract_initial_probs() returns the initial-state probabilities of a
network: the share of sequences that start in each state. It reads a
netobject (or any list) that stores them as initial, initial_probs,
inits or initial_probabilities, a tna-family object that stores
them as initial, initial_probs or inits (models from the tna
package store inits), or an mcml (one vector per layer).
Of the build_network() methods, the transition methods ("relative",
"frequency", "attention", "ngram", "gap" and "reverse") store
initial probabilities, as do wtna() transition networks. For
co-occurrence and association networks, and for a model that keeps them
under another name, the function returns a uniform distribution over the
states of the weight matrix, with a warning: those values are a
placeholder, not an estimate.
Usage
extract_initial_probs(model)
## S3 method for class 'nest_initial_probs'
print(x, ...)
## S3 method for class 'nest_initial_probs'
summary(object, ...)
Arguments
model |
The network: a |
x |
For the |
... |
For the |
object |
For the |
Value
For a single network: a named numeric vector of initial-state
probabilities that sums to 1 (stored values are rescaled when their sum
differs from 1 by more than 1e-6), of class c("nest_initial_probs", "numeric"). summary() returns a data frame with one row per state and
the columns state and prob, sorted by decreasing probability.
For a group of networks (netobject_group): a data frame with one row
per network and state and the columns group, state and prob, the
states in each network's order.
For an mcml: a named list of plain numeric vectors, macro first and
then one per cluster, taken as stored in each layer (inits).
See Also
extract_transition_matrix for extracting the transition matrix,
extract_edges for extracting an edge list.
Examples
seqs <- data.frame(V1 = c("A","B","A"), V2 = c("B","A","C"), V3 = c("A","C","B"))
net <- build_network(seqs, method = "relative")
init_probs <- extract_initial_probs(net)
print(init_probs)
Cut an event log into pathways
Description
extract_pathways() cuts a long event log into pathways, runs of
consecutive events within one unit (an actor, or an actor's session), and
returns them as a data frame with one row per pathway, ready to tabulate
against an outcome or to pass to a sequence model. Three cuts are
available through type: each unit as one pathway, consecutive segments
that each end on a terminal state, or one pathway from every occurrence of
an anchor state to the next terminal state.
With terminal, the cuts keep only what reaches a terminal state: a
unit without one, events after a unit's last terminal state, and anchors
with no later terminal state are left out without a message, so count
the units and events kept before comparing pathway frequencies across
groups.
Usage
extract_pathways(
data,
action,
group,
order = NULL,
type = c("unit", "segments", "anchored"),
anchor = NULL,
terminal = NULL,
resolve = NULL,
sep = " -> "
)
Arguments
data |
A long data frame with one row per event, in time order
within each unit unless |
action |
The name of the column holding each event's state. |
group |
The names of the columns defining the unit a pathway may not cross, typically the actor, or the actor and the session. |
order |
The name of a column giving the order of events within a
unit; the rows are sorted by |
type |
The cut to make:
|
anchor |
The single state that opens a pathway when |
terminal |
The states that close a pathway, the closing state
included. Required for |
resolve |
A named list that appends a resolution label as each
pathway's final state. Each element is a character vector of states; a
pathway takes the name of the first element whose states all occur in
it, so order the list from most to least specific, and pathways
matching none are labelled |
sep |
The separator placed between states in |
Value
A data frame with one row per pathway, in the order the pathways
occur within each unit. Units appear in the order they first occur in
data, or sorted by group when order is given and when type = "unit" is combined with terminal. Columns: the group columns,
pathway (the pathway's number within its unit, from 1), path (the
states joined with sep), length (the number of states), opens
(the first state) and closes (the last state). With resolve,
closes holds the resolution label and an ends column the observed
last state. When no pathway is found
(for example, the anchor or the terminal states never occur), an error
of class nestimate_no_pathway is raised.
See Also
sequence_compare, outcome_model
Examples
log <- data.frame(
id = c(1, 1, 1, 1, 1, 1, 2, 2, 2),
act = c("Try", "Wrong", "Hint", "Retry", "Right", "Praise",
"Try", "Wrong", "Retry"),
stringsAsFactors = FALSE
)
# Each failure and its consequence:
extract_pathways(log, action = "act", group = "id", type = "anchored",
anchor = "Wrong", terminal = c("Right", "Wrong"))
# Each id as one episode:
extract_pathways(log, action = "act", group = "id")
Extract sequences in wide format
Description
extract_sequences() returns the sequences behind a Nestimate input as a
wide data frame, one row per sequence and one column per position. It
reads the output of prepare(), a long event log (with action set), a
wide data frame or character matrix, a netobject, netobject_group or
cograph_network built from sequences, and a tna model; networks and
models give back their stored, decoded states. The sequence verbs, such
as sequence_metrics() and sequence_patterns(), read their input the
same way.
Column roles are declared, never guessed: an event log needs action,
and a wide table needs its positions named as a numbered run or listed in
cols. When the positions were listed and their names are not a run,
the result records them, so it can be passed to another sequence verb
without cols again (not when meta = TRUE adds covariate columns).
Usage
extract_sequences(
x,
cols = NULL,
actor = NULL,
action = NULL,
time = NULL,
meta = FALSE,
...
)
Arguments
x |
The sequence data: a |
cols |
The state columns of a wide data frame; the other columns
are the sequences' covariates. Default |
actor, action, time |
The actor, action and timestamp columns of a
long event log. Setting |
meta |
Whether to put the covariate columns of each sequence
(actor, session, group, metadata) before the state columns; a grouped
network adds its grouping column among them. Default |
... |
Further arguments passed to |
Value
A data frame with one row per sequence. The state columns are
character, NA after a sequence ends and at missing positions (empty
strings and TraMineR's void % and missing * markers are read as
NA). Their names are the position names of the input (T1, T2,
... for prepared or long data, V1, V2, ... for an unnamed matrix).
With meta = TRUE the covariate columns come first. Input that holds
no observed state raises an error of class nestimate_bad_input.
See Also
Examples
extract_sequences(trajectories)
extract_sequences(group_regulation_long, actor = "Actor",
action = "Action", time = "Time", meta = TRUE)
net <- build_tna(trajectories)
extract_sequences(net)
Extract the transition matrix of a network
Description
extract_transition_matrix() returns the weight matrix of a network: for
a transition network, the transition probabilities or counts between
states, with rows as the states moved from and columns as the states
moved to. It reads a netobject (or any list with a weights element), a
tna, ftna, ctna or atna model, an mcml (one matrix per layer) or
a bare matrix, and can rescale the rows to sum to 1.
Usage
extract_transition_matrix(model, type = c("raw", "scaled"))
## S3 method for class 'nest_transition_matrix'
print(x, ...)
## S3 method for class 'nest_transition_matrix'
summary(object, ...)
Arguments
model |
The network: a |
type |
Which matrix to return. |
x |
For the |
... |
For the |
object |
For the |
Details
Models store their weights in different places; the function looks in
each in turn. "scaled" is useful when the stored weights are counts or
otherwise do not sum to 1 per row.
Value
For a single network: a square numeric matrix with the model's
state names (if any) as row and column names, of class
c("nest_transition_matrix", "matrix", "array"). It behaves as an
ordinary matrix in arithmetic and indexing; summary()
returns a data frame with one row per non-zero entry (self-transitions
included) and the columns from, to and weight, sorted by
decreasing absolute weight.
For a group of networks (netobject_group): a named list of such
matrices, one per network; extract_edges() gives the same weights as
one data frame with a group column.
For an mcml: a named list of such matrices, macro first and then
one per cluster.
See Also
extract_initial_probs for extracting initial probabilities,
extract_edges for extracting an edge list.
Examples
seqs <- data.frame(V1 = c("A","B","A"), V2 = c("B","A","C"), V3 = c("A","C","B"))
net <- build_network(seqs, method = "relative")
trans_mat <- extract_transition_matrix(net)
print(trans_mat)
Count the transitions between states in sequences
Description
frequencies() counts how often each state is followed by each other
state across all sequences and returns the counts as a square integer
matrix. It reads an event log (one row per event, action set) or a wide
table (one row per sequence, one column per position).
Usage
frequencies(
data,
action = NULL,
id = NULL,
time = NULL,
cols = NULL,
format = c("auto", "long", "wide")
)
## S3 method for class 'nest_transition_counts'
summary(object, ...)
Arguments
data |
A data frame of sequences: an event log or a wide table. |
action |
The column holding each event's state; setting it declares
an event log. Default |
id |
The column(s) identifying sequences. Default |
time |
The column that orders the events of each sequence in an
event log. Default |
cols |
The state columns of a wide table; setting them declares a
wide table. Default |
format |
How to read |
object |
For the |
... |
For the |
Details
In an event log, the sequences are defined by the id
column(s), and the events of each sequence are ordered by time (events
sharing a time keep their row order) or, without time, by row order.
Each pair of consecutive events is one transition.
In a wide table, each row is a sequence and the state columns are consecutive positions; each pair of adjacent positions is one transition.
In both, a missing state (NA or an empty string) breaks the sequence: no
transition is counted into or out of it, and the states on either side
are not joined. convert_sequence_format() closes such gaps instead.
Value
A square integer matrix of transition counts, of class
c("nest_transition_counts", "matrix", "array"), where mat[i, j] is
the number of times state i was followed by state j; the row and column
names are the sorted unique states. It behaves as an ordinary matrix and
can be passed directly to tna::tna(). Its summary() returns the same
counts as a data frame with one row per non-zero transition and columns
from, to and count.
See Also
convert_sequence_format for converting to other
representations (frequency counts, one-hot, edge lists).
Examples
# Wide format
seqs <- data.frame(V1 = c("A","B","A"), V2 = c("B","A","C"), V3 = c("A","C","B"))
freq <- frequencies(seqs, format = "wide")
# Long format
long <- data.frame(
Actor = rep(1:2, each = 3), Time = rep(1:3, 2),
Action = c("A","B","C","B","A","C")
)
freq <- frequencies(long, action = "Action", id = "Actor")
Retrieve a registered estimator
Description
get_estimator() returns the registry entry of one estimator: its
function, description and directedness, as build_network() uses them. A
name that is not registered raises an error that lists the registered
names. Method aliases such as "tna" are not resolved here; give the
registered name, as list_estimators()
shows it.
Usage
get_estimator(name)
Arguments
name |
The registered name of the estimator, a single string. |
Value
A list with fn (the estimator function), description (a
string) and directed (TRUE or FALSE).
Note
The idiographic package exports a function with the same
name. With both packages attached, the one attached last masks the
other; write Nestimate::get_estimator() to call this one.
See Also
register_estimator, list_estimators
Examples
est <- get_estimator("relative")
Group regulation actions in collaborative learning
Description
group_regulation_long is a coded dataset of students' regulation
actions during collaborative learning: 27,533 timestamped actions by
2,000 students working in 200 groups across three courses. It is in long
format, one row per action.
Usage
group_regulation_long
Format
A data frame with 27,533 rows and 6 columns:
- Actor
Integer student identifier, 1 to 2,000.
- Achiever
Character achievement level,
"High"or"Low".- Group
Numeric collaboration group identifier, 1 to 200; each student belongs to one group.
- Course
Character course identifier,
"A","B"or"C".- Time
POSIXct timestamp of the action.
- Action
Character regulation action, one of adapt, cohesion, consensus, coregulate, discuss, emotion, monitor, plan and synthesis.
Source
Synthetically generated from the group_regulation dataset
in the tna package.
See Also
learning_activities, srl_strategies
Examples
net <- build_network(group_regulation_long,
method = "relative",
actor = "Actor", action = "Action", time = "Time")
net
Compute the eigenvector centralities of a hypergraph
Description
hypergraph_centrality() scores how central each node of a hypergraph
is, with up to three eigenvector centralities from Benson (2019):
clique-motif (CEC, "clique"), Z-eigenvector (ZEC, "Z") and
H-eigenvector (HEC, "H"). CEC flattens the groups into pairs by clique
expansion and takes the eigenvector centrality of that pairwise graph.
ZEC and HEC work on the hyperedges directly: a node's score grows with
the product of the scores of the other members of each hyperedge it
belongs to. It reads a net_hypergraph from build_hypergraph() or
bipartite_groups().
The variants can rank the nodes differently, since CEC counts shared
memberships pair by pair while ZEC and HEC weigh each group as a whole.
ZEC and HEC are defined for uniform hypergraphs only, where every
hyperedge of two or more members has the same size. On a disconnected
hypergraph, compare scores within one component: CEC gives zero to every
component whose leading eigenvalue is below the largest, and the
Z-eigenvector is not unique.
hypergraph_measures() describes the structure the scores come from.
Usage
hypergraph_centrality(
hg,
type = "clique",
max_iter = 1000L,
tol = 1e-08,
normalize = TRUE
)
Arguments
hg |
A hypergraph, from |
type |
The centralities to compute, any of |
max_iter |
The largest number of power-iteration steps for |
tol |
The convergence tolerance for |
normalize |
How each vector is scaled. |
Details
Clique-motif eigenvector centrality (CEC) is the leading eigenvector
of the clique-expanded pairwise graph W with
W_{ij} = |\{e : i, j \in e\}|, the number of hyperedges two
nodes share. It reads membership only (a positive incidence cell, the
rule that builds $hyperedges), so incidence weights are ignored:
it equals igraph::eigen_centrality() on
clique_expansion(hg, weighted = FALSE), and on clique_expansion()'s
default output only for an unweighted hypergraph. The vector is solved
directly from a symmetric eigendecomposition of each connected component
(Perron-Frobenius makes the leading eigenvalue of a connected component
simple), not by power iteration, which oscillates when the clique
expansion is bipartite (for example a star of pairs). When several
components share the largest eigenvalue, the result is the projection of
the uniform vector onto their joint leading eigenspace; components with a
smaller leading eigenvalue score zero.
Z-eigenvector centrality (ZEC) solves the eigen-equation on the hyperedge tensor,
\lambda\, x_i \;=\; \sum_{e \ni i}\; \prod_{j \in e,\; j \neq i} x_j,
by a shifted power iteration (a variant of SS-HOPM, Kolda & Mayo, 2011,
that normalises the tensor step before adding the shift). Tensor products
and normalisation are evaluated in log space, so the centralities stay
finite and normalised for large hyperedges. Besides the step tolerance,
the iteration checks that the eigen-equation residual is small (relative
residual at most max(sqrt(tol), 1e-6)); otherwise it warns.
H-eigenvector centrality (HEC) solves, by the same iteration,
\lambda\, x_i^{k-1} \;=\; \sum_{e \ni i}\; \prod_{j \in e,\; j \neq i} x_j.
Uniform hypergraphs only. Benson (2019) defines ZEC and HEC for
k-uniform hypergraphs. With mixed sizes the right-hand side mixes
polynomial degrees, so the equation has no scale-free solution: the
vector satisfies it only at the normalisation chosen inside the
iteration. Hyperedges with one member contribute nothing and are ignored
by the uniformity check. For mixed sizes use "clique", or keep one
size with build_hypergraph() (include_pairwise = FALSE).
Disconnected hypergraphs. The Z-eigenvector is not unique when the
hypergraph has several components: different iterations can solve the
equation with different vectors, so compare "Z" values within one
connected hypergraph only.
Value
A named list with one numeric vector per requested type, in the
order given, each with one value per node of hg, named by the nodes.
A hypergraph with no hyperedges, or with only one-member hyperedges,
gives all-zero vectors, and one without nodes empty vectors.
Note
The "clique" (CEC) variant is validated against
igraph::eigen_centrality() (cosine ~ 1). The "Z" and "H" variants
are experimental: they are validated only against a clean-room
list-based tensor power iteration (the same operator with a different
loop structure), as no R package exposes tensor eigenvectors for an
independent comparison.
References
Benson, A. R. (2019). Three hypergraph eigenvector centralities. SIAM Journal on Mathematics of Data Science 1(2), 293-312. arXiv:1807.09644.
Kolda, T. G., & Mayo, J. R. (2011). Shifted power method for computing tensor eigenpairs. SIAM Journal on Matrix Analysis and Applications 32(4), 1095-1124. doi:10.1137/100801482
See Also
build_hypergraph(), clique_expansion(),
hypergraph_measures().
Examples
df <- data.frame(
player = c("A", "B", "C", "A", "B", "D", "C", "D", "E"),
session = c("S1", "S1", "S1", "S2", "S2", "S3", "S3", "S3", "S3")
)
hg <- bipartite_groups(df, "player", "session")
hypergraph_centrality(hg)
# Z and H need a uniform hypergraph: here every session has three players
df3 <- data.frame(
player = c("A", "B", "C", "A", "B", "D", "C", "D", "E"),
session = c("S1", "S1", "S1", "S2", "S2", "S2", "S3", "S3", "S3")
)
hypergraph_centrality(bipartite_groups(df3, "player", "session"),
type = c("clique", "Z", "H"))
Cluster the nodes of a hypergraph spectrally
Description
hypergraph_cluster() partitions the nodes of a hypergraph into k
clusters with the spectral algorithm of Hayashi et al. (2020,
"RDC-Spec"): it takes the eigenvectors of the k smallest eigenvalues of
the normalised Laplacian from hypergraph_laplacian(), scales each
node's row of them to unit length, and clusters the rows with k-means.
It works with either Laplacian. With type = "random_walk" and a
weighted incidence (for example from bipartite_groups() with
weight), the edge-dependent vertex weights can change the partition;
with edge-independent weights the walk reduces to a random walk on a
graph (Chitra & Raphael 2019).
The eigengap, the distance between the k-th and the next eigenvalue,
shows how well the spectrum separates k groups: a large gap supports
k, a small one means the spectrum does not single it out. plot()
draws the spectrum, so neighbouring values of k can be compared.
k-means is stochastic, so a partition that matters is worth refitting
with other seeds to see whether it holds.
Usage
hypergraph_cluster(
hg,
k,
type = c("zhou", "random_walk"),
edge_weights = NULL,
nstart = 25L,
seed = NULL
)
## S3 method for class 'net_hypergraph_cluster'
print(x, ...)
## S3 method for class 'net_hypergraph_cluster'
summary(object, ...)
node_clusters(x)
## S3 method for class 'net_hypergraph_cluster'
plot(x, what = c("both", "spectrum", "embedding"), n_values = NULL, ...)
Arguments
hg |
The hypergraph: a connected |
k |
The number of clusters, a whole number from 2 to one less than the number of nodes. Required; a value that is not a single whole number in that range raises an error. |
type, edge_weights |
The Laplacian and its hyperedge weights, passed
to |
nstart |
The number of random starts k-means tries, keeping the
best. Default |
seed |
A whole number that makes the k-means starts reproducible.
The session's own random stream is left as it was. Default |
x |
For |
... |
For the methods: ignored. |
object |
For the |
what |
For the |
n_values |
For the |
Value
A net_hypergraph_cluster object. print() reports the
Laplacian, the cluster sizes and the eigengap; summary() returns one
row per cluster; plot() draws the spectrum and the embedding. The
object's fields:
- clusters
A data frame with one row per node:
nodeandcluster. Clusters are labelled"Cluster 1","Cluster 2", ... in the order they first appear among the nodes.- embedding
The node-by-
kspectral embedding k-means clustered, each row of unit length, with columnsdim1todimk.- k, type
The number of clusters and the Laplacian type.
- eigenvalues
The full spectrum of the Laplacian, increasing.
- eigengap
The
(k + 1)-th minus thek-th eigenvalue.- sizes
A data frame of
clusterandsize.- pi
The stationary distribution of the walk, named by node.
- n_nodes, n_hyperedges
The size of the hypergraph.
- params
The
edge_weightsused,nstart,seedand the k-means total within-cluster sum of squares (tot_withinss).
The print() method returns its input invisibly. The summary()
method returns a data frame with one row per cluster: cluster, size
and share (the proportion of nodes). node_clusters()
returns a data frame with one row per node: node, cluster, pi
(the node's stationary probability under the Laplacian's walk) and the
embedding coordinates dim1 to dimk. The plot() method returns a
ggplot for "spectrum" or "embedding". For "both" it draws the
two panels and returns the arranged gtable invisibly when
gridExtra is installed, and otherwise draws them in grid
viewports and returns the two ggplots as a list, invisibly.
References
Hayashi, K., Aksoy, S. G., Park, C. H., & Park, H. (2020). Hypergraph random walks, Laplacians, and clustering. CIKM 2020, 495-504. doi:10.1145/3340531.3412034
Chitra, U., & Raphael, B. J. (2019). Random walks on hypergraphs with edge-dependent vertex weights. ICML 2019.
Examples
events <- data.frame(
person = c("a", "b", "c", "a", "b", "c", "d", "e", "f",
"d", "e", "f", "c", "d"),
meeting = c("m1", "m1", "m1", "m2", "m2", "m2", "m3", "m3", "m3",
"m4", "m4", "m4", "m5", "m5")
)
hg <- bipartite_groups(events, player = "person", group = "meeting")
cl <- hypergraph_cluster(hg, k = 2, seed = 1)
cl
node_clusters(cl)
Compute the normalised Laplacian of a hypergraph
Description
hypergraph_laplacian() computes the normalised Laplacian of a hypergraph
and returns it as a symmetric node-by-node matrix. hypergraph_cluster() and hypergraph_transduction() are built on it. It
comes in two forms. type = "zhou" is the Laplacian of Zhou, Huang and
Schölkopf (2006), computed on the binary incidence pattern, so
the values in the incidence cells play no part. type = "random_walk" is
the Laplacian of Hayashi et al. (2020) for a random walk with
edge-dependent vertex weights: the weighted incidence cells (for example
the summed weights bipartite_groups() produces with weight) set where
a walker that enters a hyperedge lands, and the walk, which is not
reversible, is symmetrised through its stationary distribution (Chung
2005). Only a positive cell makes a node a member: a cell that is zero or
negative (a net-negative summed weight) is not part of the hyperedge and
carries no weight in either form.
Both Laplacians are symmetric positive semi-definite with eigenvalues in
[0, 2]. On a binary incidence with unit hyperedge weights the two forms
coincide. The hypergraph must be connected, so the eigenvalue 0 occurs
once; further eigenvalues close to 0 indicate groups of nodes that the
walk seldom leaves, which is what hypergraph_cluster() partitions by.
Usage
hypergraph_laplacian(hg, type = c("zhou", "random_walk"), edge_weights = NULL)
Arguments
hg |
A hypergraph, from |
type |
The Laplacian. |
edge_weights |
Positive hyperedge weights, one per hyperedge in the
order of the incidence columns. Default |
Details
For "zhou", with H the binary incidence, W the diagonal of
hyperedge weights, D_e the hyperedge sizes and D_v the node
degrees (the summed weights of the hyperedges a node belongs to),
L = I - D_v^{-1/2} H W D_e^{-1} H^T D_v^{-1/2},
and the stationary distribution is proportional to D_v. For
"random_walk", a walker at node v picks a hyperedge containing
it with probability proportional to its weight, then a node u of
that hyperedge with probability proportional to the incidence cell
\gamma_e(u). The stationary distribution \pi is the leading
left eigenvector of this transition matrix P, and
L = I - (\Pi^{1/2} P \Pi^{-1/2} + \Pi^{-1/2} P^T \Pi^{1/2}) / 2.
The random-walk Laplacian, its stationary distribution and its default
hyperedge weights follow the reference implementation in HyperNetX
(laplacians_clustering.py).
Value
A symmetric numeric matrix with one row and one column per node
(the node names as dimnames). Its attributes record the type, pi
(the stationary distribution of the walk, named by node) and
edge_weights (the hyperedge weights used).
References
Zhou, D., Huang, J., & Schölkopf, B. (2006). Learning with hypergraphs: Clustering, classification, and embedding. NeurIPS 19.
Hayashi, K., Aksoy, S. G., Park, C. H., & Park, H. (2020). Hypergraph random walks, Laplacians, and clustering. CIKM 2020, 495-504. doi:10.1145/3340531.3412034
Chung, F. (2005). Laplacians and the Cheeger inequality for directed graphs. Annals of Combinatorics, 9(1), 1-19.
Examples
events <- data.frame(
person = c("a", "b", "c", "a", "b", "d", "c", "d", "e", "e", "a"),
meeting = c("m1", "m1", "m1", "m2", "m2", "m2", "m3", "m3", "m3",
"m4", "m4"),
hours = c(2, 1, 1, 3, 2, 1, 2, 2, 4, 1, 1)
)
hg <- bipartite_groups(events, player = "person", group = "meeting",
weight = "hours")
L <- hypergraph_laplacian(hg, type = "random_walk")
range(eigen(L, symmetric = TRUE, only.values = TRUE)$values)
Compute the structural measures of a hypergraph
Description
hypergraph_measures() computes the structural statistics of a
hypergraph at three levels: for each node (how many hyperedges it
belongs to, how large they are, and how many it shares with each other
node), for each hyperedge and pair of hyperedges (their sizes and how
much they overlap), and for the hypergraph as a whole (density, mean
hyperedge size, the intersection profile). It reads the net_hypergraph
objects that build_hypergraph() and bipartite_groups() return.
The measures describe the hypergraph as observed: they carry no
uncertainty and test nothing. The intersection profile shows whether
hyperedges mostly share no or few nodes or share substantial cores (Do
et al., 2020; Lee, Choe & Shin, 2021). To rank nodes by their position
in the hypergraph, use hypergraph_centrality(); to read it as an
ordinary pairwise network, project it with clique_expansion().
Usage
hypergraph_measures(hg)
## S3 method for class 'hypergraph_measures'
print(x, ...)
Arguments
hg |
A |
x |
For the |
... |
For the |
Details
All measures are matrix operations on the binary incidence matrix
B = (b_{ij}), where b_{ij} = 1 if node i is in
hyperedge j; a weighted incidence is binarised first:
-
hyperdegree = rowSums(B),edge_sizes = colSums(B) -
co_degree = tcrossprod(B)(with zero diagonal) -
edge_pairwise_overlap = crossprod(B)(with zero diagonal) -
overlap_coefficient[i, j] = overlap[i, j] / min(edge_sizes[i], edge_sizes[j]) -
jaccard[i, j] = overlap[i, j] / (edge_sizes[i] + edge_sizes[j] - overlap[i, j])
A ratio whose denominator is 0 is set to 0.
A hypergraph without hyperedges (n_hyperedges == 0) gives zeros for
the node measures, empty hyperedge matrices, a density and pairwise
participation of 0, and an avg_edge_size of NA.
Value
A hypergraph_measures object, a named list; print() shows the
density, mean hyperedge size and pairwise participation, the minimum,
median and maximum of hyperdegree, node strength and hyperedge size,
and the intersection profile, and returns its input invisibly.
Its components, node-level first:
- Node-level (one value per node)
hyperdegreeThe number of hyperedges containing each node.
node_strengthTotal participation: for node
i,\sum_{e \ni i} |e|. A node in many large hyperedges has high strength.max_edge_sizeThe size of the largest hyperedge containing each node (0 for a node in none).
co_degreeAn
n_nodesxn_nodesmatrix:co_degree[i, j] = |{e : i, j in e}|, the number of hyperedges containing both nodesiandj. The diagonal is zero.- Hyperedge-level (one value per hyperedge, or m x m)
edge_sizesThe hyperedge sizes
|e|.edge_pairwise_overlapAn
mxmmatrix of|e_i intersect e_j|. The diagonal is zero.overlap_coefficientAn
mxmmatrix of|e_i intersect e_j| / min(|e_i|, |e_j|): how much of the smaller hyperedge lies in the larger. The diagonal is zero.jaccardAn
mxmmatrix of the symmetric overlap index|e_i intersect e_j| / |e_i union e_j|. The diagonal is zero.- Global (scalars)
densityFor a hypergraph whose hyperedges all have size
k:m / choose(n, k). For mixed sizes:sum(|e|) / (n * m), the mean fraction of nodes per hyperedge.avg_edge_sizeThe mean of
edge_sizes.size_distributionThe count of hyperedges of each size, passed through from
hg.intersection_profileThe number of hyperedge pairs at each intersection size that occurs, named
overlap_<size>(sizes with no pairs are left out); empty with fewer than two hyperedges.pairwise_participationThe fraction of node pairs that appear together in at least one hyperedge (0 with fewer than two nodes).
n_nodes,n_hyperedgesThe numbers of nodes and hyperedges.
References
Lee, G., Choe, M., & Shin, K. (2021). How do hyperedges overlap in real-world hypergraphs? Patterns, measures, and generators. Proceedings of the Web Conference 2021, 3396-3407.
Do, M. T., Yoon, S., Hooi, B., & Shin, K. (2020). Structural patterns and generative models of real-world hypergraphs. arXiv:2006.07060.
See Also
build_hypergraph(), bipartite_groups(),
hypergraph_centrality(), clique_expansion().
Examples
df <- data.frame(
player = c("A", "B", "C", "A", "B", "D", "C", "D"),
session = c("S1", "S1", "S1", "S2", "S2", "S3", "S3", "S3")
)
hg <- bipartite_groups(df, "player", "session")
m <- hypergraph_measures(hg)
print(m) # node-level, hyperedge-level and global measures
Classify unlabelled hypergraph nodes by label spreading
Description
hypergraph_transduction() classifies the unlabelled nodes of a
hypergraph from a few labelled ones, by the label-spreading framework of
Zhou et al. (2006). The labels spread over the hypergraph as the scores
F = (1 - \xi) (I - \xi S)^{-1} Y,
where S = I - L is the similarity operator of the chosen Laplacian
(see hypergraph_laplacian()) and Y marks each labelled node's
class, and each node is assigned the class with the highest score. This
is the non-neural ancestor of hypergraph-attention text classifiers: with
documents as hyperedges over words (or the reverse), it classifies
unlabelled nodes from a handful of labelled ones.
The margin of a node, its winning minus its runner-up score, says how
clearly it was assigned; assignments with a small margin are the ones to
distrust. The given labels are not held fixed, so a labelled node can be
predicted into another class, and a class's scores grow with its number
of labelled nodes. As xi approaches 1, every node's scores become
proportional to the same vector, so in the limit every node is assigned
the same class. The default 0.99 is the value of Zhou et al. (2006) and
suits large hypergraphs; on a small one it over-smooths. In the example
below it assigns five of the six nodes to one class, where xi = 0.9
splits them three and three, so on a small hypergraph pass a smaller
xi and compare.
Usage
hypergraph_transduction(
hg,
labels,
xi = 0.99,
type = c("zhou", "random_walk"),
edge_weights = NULL
)
## S3 method for class 'net_hypergraph_transduction'
print(x, ...)
## S3 method for class 'net_hypergraph_transduction'
summary(object, ...)
label_predictions(x)
label_scores(x)
## S3 method for class 'net_hypergraph_transduction'
plot(x, ...)
Arguments
hg |
The hypergraph: a connected |
labels |
The known class labels, in one of two forms: a vector
named by node, covering some of the nodes, or an unnamed vector with one
entry per node, in the hypergraph's node order, and |
xi |
The spreading coefficient, a number strictly between 0 and 1.
Larger values give the hypergraph structure more weight relative to the
given labels. Default |
type, edge_weights |
The Laplacian and its hyperedge weights, passed
to |
x |
For |
... |
For the methods: ignored. |
object |
For the |
Value
A net_hypergraph_transduction object. print() reports the
Laplacian, xi, the classes and how many nodes each was predicted
for; summary() returns one row per class; plot() draws the
node-by-class score heatmap. The object's fields:
- predictions
A data frame with one row per node:
node,label(the given label,NAfor an unlabelled node),predicted,score(the winning class's score) andmargin(the winning minus the runner-up score).- classes
The classes, sorted.
- scores
The node-by-class score matrix.
- xi, type
The spreading coefficient and the Laplacian type.
- n_labeled, n_nodes
The numbers of labelled and of all nodes.
- params
The
edge_weightsused.
The print() method returns its input invisibly. The summary()
method returns a data frame with one row per class: class,
n_labeled, n_predicted and mean_margin (the mean margin of the
nodes predicted into the class, NA when there are none).
label_predictions() returns a data frame with one row per node:
node, label (NA for an unlabelled node), predicted, score and
margin. label_scores() returns a data frame with one row per node
and class: node, class and score. The plot() method
returns the score heatmap as a ggplot, visibly, so plot(x) draws
it: one row per node, grouped by
predicted class and ordered by margin within it, one column per class,
the tiles shaded and labelled by score. Labelled nodes have a black
border on their given class, and a dot marks each node's winning class,
so seeds, scores and assignments can be compared in one panel.
References
Zhou, D., Huang, J., & Schölkopf, B. (2006). Learning with hypergraphs: Clustering, classification, and embedding. NeurIPS 19.
Examples
events <- data.frame(
person = c("a", "b", "c", "a", "b", "c", "d", "e", "f",
"d", "e", "f", "c", "d"),
meeting = c("m1", "m1", "m1", "m2", "m2", "m2", "m3", "m3", "m3",
"m4", "m4", "m4", "m5", "m5")
)
hg <- bipartite_groups(events, player = "person", group = "meeting")
tr <- hypergraph_transduction(hg, labels = c(a = "x", d = "y"), xi = 0.9)
tr
label_predictions(tr)
label_scores(tr)
Tabulate the item loadings of a psychometric MCML fit
Description
item_loadings() returns the item table behind a build_mcml_pc() fit:
one row per item, with how strongly the item connects to its own cluster,
the weight it carries into that cluster's score, and whether it connects
more strongly to some other cluster. The loadings are network loadings,
read from the node-level network (an item's mean absolute connection to
the members of a cluster), not factor loadings.
An item flagged as misfit connects more strongly to another cluster than
to its own, which is evidence that it is assigned to the wrong cluster;
every aggregation of the fit inherits that membership. A sign of -1
marks an item treated as reverse-keyed. How stable the weights are under
resampling is checked with loading_stability().
Usage
item_loadings(x, ...)
## S3 method for class 'mcml_pc'
item_loadings(x, misfit = NULL, ...)
Arguments
x |
An |
... |
Ignored. |
misfit |
Which items to return: |
Value
A data frame with one row per item (only the misfitting or the
fitting items when misfit is set) and columns node, cluster,
loading (the mean absolute connection to the other members of its own
cluster, signed by the leading eigenvector of the cluster's block; under
a sign-carrying weighting the sign column holds the sign actually
used, which can differ), weight (its weight in the cluster
score, or its strength weight for a descriptive aggregation; the weights
of a cluster sum to 1), sign (+1, or -1 for a
reverse-keyed item), max_cross (its strongest mean absolute
connection to any other cluster), cross_cluster (which cluster that
is) and misfit (logical). An item alone in its cluster has loading 0,
weight 1 and is never flagged.
See Also
build_mcml_pc to create the fit,
loading_stability for the weights' sampling
uncertainty, composites for the scores these weights
produce.
Examples
set.seed(1)
f <- stats::rnorm(200)
g <- stats::rnorm(200)
df <- data.frame(a1 = f + stats::rnorm(200), a2 = f + stats::rnorm(200),
a3 = f + stats::rnorm(200), b1 = g + stats::rnorm(200),
b2 = g + stats::rnorm(200), b3 = g + stats::rnorm(200))
clusters <- list(A = c("a1", "a2", "a3"), B = c("b1", "b2", "b3"))
fit <- build_mcml_pc(df, clusters, aggregation = "loadings",
method = "cor")
item_loadings(fit)
item_loadings(fit, misfit = TRUE)
Trace a stability landscape across a sequence measure
Description
landscape_surface() traces the cups of stability_landscape() over a
second axis, a per-sequence stability measure from sequence_metrics()
such as self-loop tendency or longitudinal entropy, and returns the cup
depth of every state at each point of that axis. At each of n_grid
values of the measure, sequences are weighted by a tricube kernel on their
distance to that value over the k nearest (Cleveland 1979), and each
state's cup depth, -\log(1 - P_{ii}) (the log of its expected
stay), is computed from their weighted pooled transitions. With the
default measure, longitudinal entropy, moving up the axis goes from the
most stable to the most volatile sequences; for a measure where higher
means more stable (self-loop tendency, spell durations, initial-state
persistence, dominant-state share) it goes the other way. Several
measures give one surface each, and a grouped network one set per group.
The measures are computed from the same sequences as the depths, so the
cups of the most stable sequences are deep by construction (self-loop
tendency in particular is closely tied to the stay probabilities). What
the surface adds is which cup deepens as stability rises. A slice's
effective_n ((\sum w)^2 / \sum w^2) shows how many sequences it
rests on, and a warning of class nestimate_thin_slice flags slices
resting on fewer than five. For change over time rather than
across sequences, use landscape_trend().
Usage
landscape_surface(
x,
measure = "longitudinal_entropy",
states = NULL,
k = 30L,
n_grid = 25L,
cols = NULL
)
## S3 method for class 'net_landscape_surface'
summary(object, ends = TRUE, ...)
## S3 method for class 'net_landscape_surface'
print(x, digits = 2, ...)
## S3 method for class 'net_landscape_surface'
plot(x, max_stay = 50, theta = 10, phi = 30, ncol = NULL, ...)
Arguments
x |
The network or sequences: a transition network from
|
measure |
The per-sequence measures to trace, one surface each: one
or more numeric columns of |
states |
Every state, each named once, in drawing order. Default
|
k |
The number of nearest sequences each slice is weighted over, at
least 5. Default |
n_grid |
The number of slices, at least 2, spread evenly between the
5th and 95th percentile of the measure. If these percentiles coincide
for a measure that is not constant, its full range is used. Default
|
cols |
For a wide data frame: the columns holding the positions.
Needed when they are not a numbered run ( |
object |
For the |
ends |
For the |
... |
Ignored. |
digits |
For the |
max_stay |
For the |
theta, phi |
For the |
ncol |
For the |
Details
Network input replays the network's per-sequence weighting, concatenation and boundary markers; concatenated sequences are weighted as one unit. Scaled, thresholded or otherwise modified networks whose weights do not match their stored sequences are refused; pass the original sequences to estimate a new landscape.
Sequences with fewer than two observed positions, or no value of the
measure, are left out. The kernel's half-width is the distance to the
k-th nearest sequence, but at least 1/50 of the measure's range; when
the k nearest all lie at that distance (many sequences share a value),
they weigh equally. A state
that does not occur in a slice has an NA depth and leaves a gap in the
surface, and one that is never left in a slice has an infinite depth.
Value
A net_landscape_surface object. print() shows each state's
depth at the low and the high end of each measure and the range of
effective sequences per slice; summary() returns the tables below;
plot() draws one graphics::persp() surface per network and measure
on a shared depth scale, the most stable end of each measure in front
(for a measure with no stability direction, the low end) and the
surface shaded from green (deep) to orange (shallow). print() and
plot() return their input invisibly.
summary() returns a data frame. With ends = TRUE: one row per
network, measure and state, with group, measure, state,
low_value, depth_at_low, high_value and depth_at_high. With
ends = FALSE: one row per network, measure, slice and state, with
group, measure, value, state, depth, dwell and
effective_n.
The object's fields:
- slices
Every slice, as
summary(x, ends = FALSE)returns it.- states
The states, in drawing order.
- measure, groups
The measures traced and the network names (
"network"for a single one).- k
The number of nearest sequences per slice.
Errors
nestimate_not_markov for a network that is not a transition network;
nestimate_bad_input for an unknown, non-numeric or constant measure,
bad states, input without sequences, or a network whose weights cannot
be rebuilt from its sequences (a scaled or thresholded one included);
nestimate_landscape_unestimable for fewer than five usable sequences.
Warning nestimate_thin_slice when slices rest on fewer than five
effective sequences.
References
Cleveland, W. S. (1979). Robust locally weighted regression and smoothing scatterplots. Journal of the American Statistical Association, 74, 829–836.
Kramers, H. A. (1940). Brownian motion in a field of force and the diffusion model of chemical reactions. Physica, 7, 284–304.
See Also
stability_landscape, sequence_metrics
Examples
net <- build_network(trajectories, method = "relative")
surf <- landscape_surface(net, measure = "longitudinal_entropy",
states = c("Disengaged", "Average", "Active"))
surf
plot(surf)
Trace a stability landscape along time or a covariate
Description
landscape_trend() traces the landscape of stability_landscape() along
a second axis and returns the height of every state, with a bootstrap
interval, at each point of that axis. The axis is either time,
along = "phase": the landscape is estimated from the transitions
inside a window of window time steps that slides one step at a time; or
a numeric per-sequence covariate such as a grade, along = "grade": at
each value of the covariate it comes from the k nearest sequences,
weighted by a tricube kernel (Cleveland 1979). Intervals come from
resampling whole sequences, and the same resamples serve every window or
slice. A grouped network gives one trend per group.
Two heights are available. depth = "stay" (default) is the depth of
stability_landscape(), the log of each state's expected stay,
-\log(1 - P_{ii}); a window as long as the sequences gives that
function's values. depth = "occupancy" is the quasi-potential
-\log \pi_i of the stationary distribution, with ridges at
-\log of the symmetrised probability flux
(\pi_i P_{ij} + \pi_j P_{ji}) / 2 between neighbouring states
(Wang et al. 2008): a low cup is a state the process spends much of its
time in, a high ridge a switch it rarely makes.
Consecutive windows share all but one step and neighbouring slices most of their sequences, so neighbouring points are not independent. Along a covariate, each point describes the sequences with values near it; the trend is an association with the covariate, not its effect.
Usage
landscape_trend(
x,
along = "phase",
depth = c("stay", "occupancy"),
states = NULL,
window = 5L,
k = 30L,
n_grid = 20L,
iter = 500L,
ci_level = 0.95,
seed = NULL,
cols = NULL
)
## S3 method for class 'net_landscape_trend'
summary(object, ...)
## S3 method for class 'net_landscape_trend'
print(x, digits = 2, ...)
## S3 method for class 'net_landscape_trend'
plot(
x,
type = c("lines", "surface"),
theta = 10,
phi = 30,
state_colors = NULL,
...
)
Arguments
x |
The network or sequences: a transition network from
|
along |
The axis: |
depth |
The height: |
states |
Every state, each named once, in drawing order; with
|
window |
With |
k |
With a covariate: the number of nearest sequences each slice is
weighted over, at least 5. Default |
n_grid |
With a covariate: the number of slices, at least 2, between
its 5th and 95th percentile, with the full range used if these coincide.
Default |
iter |
The number of bootstrap resamples of sequences, a non-negative
whole number. Default |
ci_level |
The interval level, a number between 0 and 1. Default
|
seed |
A seed for the resampling. It applies to this call only: the
session's random state is restored afterwards. Default |
cols |
For a wide data frame: the columns holding the positions.
Needed when they are not a numbered run ( |
object |
For the |
... |
Ignored. |
digits |
For the |
type |
For the |
theta, phi |
For |
state_colors |
For the |
Details
Network input replays the network's per-sequence weighting, concatenation
and boundary markers, and the concatenated sequences are the resampling
units. With a covariate, its value must be constant within each
concatenated unit. Scaled, thresholded or otherwise modified networks
whose weights do not match their stored sequences are refused; pass the
original sequences to estimate a new landscape. In a network built with
params = list(weighted = TRUE), the transitions of a phase window keep
the weight of their whole sequence.
With depth = "stay", a window or slice in which a state is never left
gives an infinite depth, and one in which it does not occur gives NA.
With depth = "occupancy", ridges join the states next to each other in
states order and the last state to the first (one ridge with two
states); a window whose chain has no unique stationary distribution
(more than one closed class of states) is NA throughout, a state
outside the closed class (transient) has an infinite potential, and a
ridge never crossed is NA. Such points are kept
in summary(), left out of the lines and the surface, and counted in the
plot caption. Interval bands are clipped at the panel edge, which is set
by the estimates.
Along a covariate, sequences without its value or with fewer than two
observed positions are left out, and the kernel's half-width is the distance
to the k-th nearest sequence, but at least 1/50 of the covariate's
range; when the k nearest all lie at that distance (a covariate with
few distinct values), they weigh equally.
Value
A net_landscape_trend object. print() shows each state's
height at the first and the last window or slice and its range, and
counts the points that could not be estimated; summary() returns the
table below; plot() returns a ggplot with type = "lines", and
with type = "surface" draws the landscape and returns its input
invisibly. print() returns its input invisibly.
summary() returns a data frame with one row per network, position and
feature: group, along, value (window centre or covariate value),
label (window steps or value), feature ("well", or "ridge" with
depth = "occupancy"), state (a state, or two for a ridge), the height
(depth for "stay", potential for "occupancy"), ci_lower,
ci_upper, n_from (transitions out of the state in the window, or
their weighted sum in the slice; wells only) and dwell ("stay"
only).
The object's fields:
- table
The table
summary()returns.- states, groups
The states in drawing order and the network names (
"network"for a single one).- along, depth, window, k, iter, ci_level
The settings used.
Errors
nestimate_latency_resampling for a latency network (or a group holding
one); nestimate_single_sequence along "phase" for a network or data
resting on one sequence when iter > 0;
nestimate_not_markov for a network that is not a transition network;
nestimate_bad_input for an unknown, non-numeric or constant covariate,
a covariate that varies within a concatenated sequence, bad states, a
window longer than the sequences, input without sequences, or a network
whose weights cannot be rebuilt from its sequences (a scaled or
thresholded one included); nestimate_landscape_unestimable for fewer
than five usable sequences along a covariate.
References
Cleveland, W. S. (1979). Robust locally weighted regression and smoothing scatterplots. Journal of the American Statistical Association, 74, 829–836.
Kramers, H. A. (1940). Brownian motion in a field of force and the diffusion model of chemical reactions. Physica, 7, 284–304.
Wang, J., Xu, L., & Wang, E. (2008). Potential landscape and flux framework of nonequilibrium networks. PNAS, 105, 12271–12276.
See Also
stability_landscape, landscape_surface
Examples
net <- build_network(trajectories, method = "relative")
trend <- landscape_trend(net, along = "phase",
states = c("Disengaged", "Average", "Active"), iter = 20, seed = 1)
trend
plot(trend)
occupancy <- landscape_trend(net, depth = "occupancy", window = 6,
states = c("Disengaged", "Average", "Active"), iter = 20, seed = 1)
plot(occupancy, type = "surface")
Online learning activity indicators
Description
learning_activities is a simulated dataset of six online learning
activities (Reading, Video, Forum, Quiz, Coding, Review) recorded as
active or not for 200 students over 30 time points. Each row is one time
point of one student and marks every activity active then (1) or not
(0), one 0/1 column per activity; at least one
activity is active in every row, and several often are. Activities tend
to continue from one time point to the next. The rows of each student
are consecutive and in time order, so the data are ready for wtna()
with actor = "student".
Usage
learning_activities
Format
A data frame with 6,000 rows and 7 columns:
- student
Integer student identifier, 1 to 200, with 30 rows each.
- Reading
Integer reading indicator (0/1).
- Video
Integer video-watching indicator (0/1).
- Forum
Integer discussion-forum indicator (0/1).
- Quiz
Integer quiz or assessment indicator (0/1).
- Coding
Integer coding-practice indicator (0/1).
- Review
Integer review or revision indicator (0/1).
Examples
head(learning_activities)
List the registered estimators
Description
list_estimators() returns the estimators build_network() can call by
name: the fifteen built-ins and any added with
register_estimator(). Aliases such as
"tna" or "ebicglasso" are not listed; the Estimators section of
build_network() gives them.
Usage
list_estimators()
Value
A data frame with one row per registered estimator, sorted by
name, and columns name, description and directed (TRUE for
directed networks). With an empty registry it has no rows.
Note
The idiographic package exports a function with the same
name. With both packages attached, the one attached last masks the
other; write Nestimate::list_estimators() to call this one.
See Also
register_estimator, get_estimator
Examples
list_estimators()
Bootstrap the item weights of a psychometric MCML fit
Description
loading_stability() bootstraps the item weights of a build_mcml_pc()
fit and returns, for each item, its observed signed weight, its bootstrap mean and standard deviation, a percentile
interval and how often its sign flipped. Each replicate resamples the rows
of the raw data with replacement, re-estimates the node-level network
with the fit's estimator (cor, pcor or glasso; any other node-level
method is re-estimated as cor) and correlation type, and reapplies the
fitted weighting scheme, data-dependent and custom weights and the
factor-analysis options included. A fit with a descriptive aggregation
("average", "escoufier", "cancor") has its item-table weights, the
"strength" weights, resampled. Experimental.
Wide intervals mean the weighting should not be over-interpreted. Equal
weights keep their magnitudes in every replicate, so for them only the
sign flips carry information; a sign that flips often marks an item whose
reverse-keying is not settled by the data. Supplied numeric weights are
fixed in magnitude and sign, so their intervals have zero width and
resampling them tells nothing. The intervals describe the weights, not
the macro network: edge-weight intervals for it come from
bootstrap_network() on its macro network.
Usage
loading_stability(x, iter = 200L, ci_level = 0.05, seed = NULL)
## S3 method for class 'pc_loading_stability'
print(x, digits = 3, ...)
## S3 method for class 'pc_loading_stability'
summary(object, ...)
## S3 method for class 'pc_loading_stability'
plot(x, ...)
Arguments
x |
An |
iter |
The number of bootstrap replicates, at least 2. Default |
ci_level |
The tail level of the percentile intervals: |
seed |
An integer that makes the resampling reproducible. Default
|
digits |
For the |
... |
For the |
object |
For the |
Value
A pc_loading_stability object. print() shows the item table
and summary() returns it;
plot() draws each item's signed weight with its interval, one panel
per cluster. The object's fields:
- summary
A data frame with one row per item:
node,cluster,weight(the observed signed weight),boot_mean,boot_sd,ci_lower,ci_upperandsign_flips(the share of replicates in which the item's sign differed from the observed one).- boot_weights
The
iterx items matrix of resampled signed weights.- iter, ci_level
The settings used.
For the methods: print() returns x invisibly, plot() a
ggplot.
For the summary() method: the item table, a data frame with one
row per item and the columns listed under summary above.
Methods
-
plot()draws each item's observed signed composite weight with its bootstrap percentile interval, one panel per cluster, with a dashed line at zero.
Examples
set.seed(1)
f <- stats::rnorm(100)
g <- stats::rnorm(100)
df <- data.frame(a1 = f + stats::rnorm(100), a2 = f + stats::rnorm(100),
a3 = f + stats::rnorm(100), b1 = g + stats::rnorm(100),
b2 = g + stats::rnorm(100), b3 = g + stats::rnorm(100))
cl <- list(A = c("a1", "a2", "a3"), B = c("b1", "b2", "b3"))
fit <- build_mcml_pc(df, cl, aggregation = "loadings",
method = "cor")
stability <- loading_stability(fit, iter = 20, seed = 1)
stability
Coded turns of human-AI vibe coding sessions
Description
human_long and ai_long are a coded dataset of the turns of 429
human-AI pair-programming ("vibe coding") sessions across 34 projects,
held between 5 February and 8 March 2026: human_long has the codes of
the human turns and ai_long those of the AI turns (428 of the sessions
have AI turns). Both are in long format, one row per code; they share
their columns and their sessions, and interleave on order_in_session.
Usage
human_long
ai_long
Format
Two data frames with the same 9 columns:
- message_id
Integer identifier of the message (turn); the codes of one message share it, and no identifier occurs in both data frames.
- project
Character project identifier,
Project_1toProject_34.- session_id
Character session identifier, a 12-character hash.
- timestamp
Integer Unix time (seconds) of midnight, UTC+2, on
session_date. It has day resolution, so the rows of one day share it;build_network(time = "timestamp")keeps tied rows in row order, which followsorder_in_session. With the defaulttime_threshold(900 seconds), each change of day also starts a new sequence, so the 84 sessions that run over more than one day are split (526 sequences instead of 429); to keep every session whole, usetime = "order_in_session".- session_date
Character date of the row (
YYYY-MM-DD); 84 sessions run over more than one day.- code
Character interaction code. The two data frames use disjoint code sets: 9 labels in
human_long(Command, Correct, Frustrate, Inquire, Interrupt, Refine, Request, Specify, Verify) and 8 inai_long(Ask, Delegate, Execute, Explain, Investigate, Plan, Repair, Report), 17 in total.- cluster
Character high-level cluster of the code.
human_longuses Directive, Evaluative and Metacognitive;ai_longuses Action, Communication and Repair.- code_order
Integer order of the code within its message, starting at 1.
- order_in_session
Integer position of the row in its session, counting the rows of both data frames together.
human_long | Human turns only, 10,796 rows |
ai_long | AI turns only, 8,551 rows |
An object of class data.frame with 10796 rows and 9 columns.
An object of class data.frame with 8551 rows and 9 columns.
Source
Saqr, M. (2026). Coded turns of human-AI vibe coding sessions (data set). Zenodo. doi:10.5281/zenodo.24528524. Described in Saqr, M. (2026), Human-AI vibe coding interaction study, saqr.me.
Examples
net <- build_network(human_long, method = "tna",
action = "code", actor = "session_id",
time = "timestamp")
net
Convert long event data to wide sequences
Description
long_to_wide() turns a long event table (one row per action) into wide
sequences, with one row per sequence and one column per position
(V1, V2, ...). Each sequence's actions are ordered by time_col, and
the k-th action fills column k.
Usage
long_to_wide(
data,
id_col = "Actor",
time_col = "Time",
action_col = "Action",
time_prefix = "V",
fill_na = TRUE
)
Arguments
data |
A data frame in long format, one row per action. |
id_col |
The column identifying each sequence. Default |
time_col |
The column that orders the actions within a sequence.
Default |
action_col |
The column holding the actions (states). Default
|
time_prefix |
The prefix of the position columns in the output.
Default |
fill_na |
How to handle sequences of different lengths. With |
Details
The wide format is the one build_network(), tna::tna() and related
functions read without column declarations, since the position columns
form a numbered run; build_network() sets the id_col column aside as
metadata, with a message.
Value
A data frame in wide format, one row per sequence in the sorted
order of id_col: the id_col column followed by the position columns
(V1, V2, ..., named with time_prefix) holding the action at each
position. Other columns of data are dropped. A missing action stays a
missing cell.
See Also
wide_to_long for the reverse conversion,
prepare_for_tna for preparing data for TNA analysis.
Examples
long_data <- data.frame(
Actor = rep(1:3, each = 4),
Time = rep(1:4, 3),
Action = sample(c("A", "B", "C"), 12, replace = TRUE)
)
wide_data <- long_to_wide(long_data, id_col = "Actor")
head(wide_data)
Build the cluster-level network with chosen clusters expanded
Description
macro_network() returns the cluster-level (macro) network of an mcml,
optionally with one or more clusters expanded back into their member
states. Every other cluster stays collapsed to a single node, so the
result is a network at mixed resolution: the cluster of interest in
detail, its context in summary, with weights counted from the sequences.
For an mcml_pc from build_mcml_pc(), it returns the cluster-level
network that fit already holds.
Usage
macro_network(
x,
expand = NULL,
method = "relative",
scaling = NULL,
threshold = 0,
params = list(),
...
)
Arguments
x |
An |
expand |
The clusters to expand into their member states. |
method |
The estimator passed to |
scaling, threshold, params |
Passed to |
... |
Further arguments for |
Details
The weights are counted again from the sequences, after each state is recoded to its cluster (or kept, for an expanded cluster), because a cluster-level matrix cannot be split back into its states.
Value
For an mcml: a netobject (also a cograph_network) whose
nodes are the collapsed clusters plus the member states of any
expanded cluster, with weights counted by build_network(). It is
printed, resampled (for example with bootstrap_network()) and drawn
like any other netobject; its node grouping is read by cograph's
group-aware plots, such as cograph::plot_mtna(). Beside the usual
netobject fields it holds node_groups, a data frame with the
columns node and group that maps each node to its cluster (an
expanded cluster's states map to that cluster, a collapsed cluster maps
to itself), the same labels as a factor in the groups column of
nodes, and
expanded, the names of the clusters expanded (NULL when none
were).
For an mcml_pc: its cluster-level network, the netobject estimated
by build_mcml_pc(), unchanged.
See Also
Examples
seqs <- data.frame(
t1 = c("A", "C", "A", "B"), t2 = c("B", "D", "C", "A"),
t3 = c("C", "A", "D", "C"), stringsAsFactors = FALSE
)
mc <- build_mcml(seqs, clusters = list(G1 = c("A", "B"), G2 = c("C", "D")))
macro_network(mc) # every cluster collapsed
macro_network(mc, expand = "G2") # G2 shown as C and D
Measure how far frequency and probability networks disagree
Description
magnitude_difference() measures, edge by edge, how far the two usual
summaries of one set of sequences disagree: the raw transition counts
(frequency network, FTNA, build_network(method = "frequency")) and the
row-conditional probabilities (TNA, build_network(method = "relative")).
It builds both networks from the same event log or wide sequences, puts
the two weight matrices on a common scale and returns the per-edge
discrepancy, the magnitude difference, under one of five metrics.
The two matrices rank edges differently because row normalisation
divides each count by its source state's total: an edge that is large in
counts can be modest in probability when its source state is frequent,
and an edge from a rare source state can dominate its row in
probability. A large magnitude difference marks an edge whose importance
depends on which view is reported; it says nothing about sampling
uncertainty, which bootstrap_network() estimates for each view.
Usage
magnitude_difference(
data,
actor = NULL,
action = NULL,
time = NULL,
metric = c("abs_diff", "chord_dist", "atanh_diff", "geom_norm_diff", "cv_inflation"),
scale = c("tna_range", "rank_minmax", "minmax", "none"),
format = c("auto", "long", "wide")
)
## S3 method for class 'magnitude_difference'
print(x, ...)
## S3 method for class 'magnitude_difference'
summary(object, n = NULL, ...)
## S3 method for class 'magnitude_difference'
plot(
x,
type = c("stacked", "circular"),
min_show = 0.01,
title = NULL,
state_colors = NULL,
...
)
Arguments
data |
The event log (long format, with |
actor, action, time |
The columns of a long event log, as in
|
metric |
The discrepancy metric, computed on the two scaled weight
vectors. |
scale |
How the two weight matrices are put on a common scale before
differencing. |
format |
The input format passed to |
x |
For the |
... |
For the
The |
object |
For the |
n |
For the |
type |
For the |
min_show |
For |
title |
For the |
state_colors |
For the |
Value
A magnitude_difference object. print() reports the metric,
the scale, the states, the number of edges and the minimum, quartiles,
mean and maximum of the magnitude differences; summary() returns the
edges, largest difference first; plot() draws them.
The object's fields:
- edges
One row per ordered pair of states (the self-transitions and absent edges included), with the columns
from,to,ftnaandtna(the scaled weights),signed(tna - ftna) andvalue(the chosen metric).- metric, scale
The metric and scale used.
- weights_ftna, weights_tna
The two scaled weight matrices.
- states
The state names.
For the plot() method: a ggplot object. The print() method
returns x invisibly.
For the summary() method: a data frame with one row per
ordered pair of states and the columns from, to, ftna, tna,
signed and value, sorted by value from largest to smallest (ties
by from, then to). A positive signed marks an edge the
probability view makes larger than the count view.
See Also
build_network(), compare_model()
Examples
data(group_regulation_long, package = "Nestimate")
fit <- magnitude_difference(group_regulation_long,
actor = "Actor", action = "Action",
time = "Time")
print(fit)
summary(fit, n = 5)
# The polar portrait shows which edges row-normalization promotes.
plot(fit) # stacked polar portrait
plot(fit, type = "circular") # chord-style diagram
Fill leading missing cells with a start state
Description
mark_first_state() fills every missing cell before each sequence's
first observed state with an explicit state, "Start" by default, and
returns the wide table. It is the counterpart of mark_terminal_state()
for left-censored data, such as students who join a course at
different times: a network built from the result shows into
which states the late entrants arrive. Internal and trailing missing
cells are left as they are, and so are rows observed from the first
position or not at all.
The marked state is a transient entry point, not an absorbing state: once a sequence leaves it, it never returns. In a transition network built from the result, its row holds the moves from it, which go to the first observed states and, for sequences with two or more leading missing cells, back to itself.
Usage
mark_first_state(data, state = "Start", cols = NULL)
Arguments
data |
The sequences: a matrix or data frame with one row per actor
and one column per position, holding state labels, with |
state |
The label written into the leading missing cells, a single
non-empty string. Default |
cols |
The columns holding the positions, in order; only they are
returned. A name not in |
Value
A data frame of character columns with the shape of data (or of
its cols), the leading missing cells filled with the marker. The label
used is kept in the "leading_state" attribute, which differs from
state when it had to be made unique. The columns are marked as
positions, so build_network() reads them without state_cols.
See Also
mark_terminal_state(), actor_endpoints()
Examples
M <- mark_first_state(trajectories, state = "Start")
# In a chain built from M, "Start" is a transient entry point.
Split each actor's sequence into phases
Description
mark_phases() divides the events of each actor into n consecutive
phases of nearly equal length and records the phase of every event in a
new column. The result can be passed to build_network() with
group = "phase" to estimate one network per phase, for example to
compare the first and second halves of each session.
The events of an actor are ordered by time (or kept in row order) and
numbered k = 1, \dots, L. Event k belongs to phase
\lceil k n / L \rceil, so the phases of one actor differ in length
by at most one event, and with an odd number of events and n = 2 the
middle event belongs to the second phase. An actor with fewer than n
events has no events in some phases.
Usage
mark_phases(
data,
actor = NULL,
time = NULL,
n = 2L,
labels = NULL,
name = "phase"
)
Arguments
data |
An event log: a data frame with one row per event. |
actor |
The column identifying whose events form one sequence (a
session, a student). Default |
time |
The column ordering the events within each actor: numeric, a
|
n |
The number of phases, a whole number of at least 2. Default |
labels |
The labels of the phases, in order, |
name |
The name of the new column. Default |
Value
data with one added character column, name, holding each
event's phase label; the rows and the other columns are unchanged and
keep their order. An absent actor or time column, missing values
in either, a time column of another type, or an invalid n or labels
raises an error of class nestimate_bad_input.
See Also
build_network() for the per-phase networks,
sequence_compare() and permutation() for comparing them.
Examples
halves <- mark_phases(human_long, actor = "session_id",
time = "order_in_session", n = 2,
labels = c("early", "late"))
head(halves)
net <- build_network(halves, method = "relative", actor = "session_id",
action = "cluster", time = "order_in_session",
group = "phase")
net
Fill trailing missing cells with an end state
Description
mark_terminal_state() fills every missing cell after each sequence's
last observed state with an explicit state, "End" by default, and
returns the wide table. This turns right-censored sequences (drop-out,
course end) into data for an absorbing-chain model: in a transition
network built from the result with build_network(), the marked state
is entered once a sequence stops and never left. Internal and leading
missing cells are left as they are, and so are rows observed to the last
position or not at all.
chain_structure() on that network gives the mean time to absorption,
the absorption probabilities and each state's classification.
markov_stability() is not the right summary for an absorbing chain:
its stationary distribution collapses onto the absorbing state.
Usage
mark_terminal_state(data, state = "End", cols = NULL)
Arguments
data |
The sequences: a matrix or data frame with one row per actor
and one column per position, holding state labels, with |
state |
The label written into the trailing missing cells, a single
non-empty string. Default |
cols |
The columns holding the positions, in order; only they are
returned. A name not in |
Details
The marked state is absorbing because each sequence that reaches it
stays there to the last column, so its only observed move is to itself
(P[state, state] = 1 in a "relative" network). That needs at least
one sequence with two or more trailing missing cells: when every
sequence stops at most one cell early, the state has no outgoing
transitions and its row in the network is zero.
Unlike build_network(end = ), which adds an end state only in the cell
after each sequence's last observed state, with no outgoing edges and no
self-loop, this function fills all the trailing cells.
Value
A data frame of character columns with the shape of data (or of
its cols), the trailing missing cells filled with the marker. The
label used is kept in the "terminal_state" attribute, which differs
from state when it had to be made unique. The columns are marked as
positions, so build_network() reads them without state_cols.
See Also
actor_endpoints(), chain_structure(), build_network()
Examples
M <- mark_terminal_state(trajectories, state = "Dropout")
net <- build_network(M, method = "relative")
chain_structure(net)
Test the Markov order of a sequential process
Description
markov_order_test() tests how many previous states are needed to
predict the next one in a set of categorical sequences: the order of the
Markov chain that describes them. At each order
k = 1, \ldots, max_order it tests the null hypothesis that order
k - 1 is enough, with the likelihood-ratio statistic G^2 for
the conditional independence s \perp x \mid w,
where w is the (k-1)-gram context, x the extra state
k steps back and s the next state. The p-value comes from a
permutation null, with the asymptotic \chi^2 p-value beside it for
reference, and the order is chosen sequentially. It reads wide sequence
tables, lists of sequences, sequence networks (single or grouped) and
prepare() results.
The order is raised while the test rejects and stops at the first
non-rejection, so the selected order is the highest k whose test,
and every test below it, rejected at alpha: 0 when order 1 is
already not rejected, and max_order when every test rejects. AIC and
BIC of the fitted chains are reported beside it and can select a
different order. With many observations even small departures from the
lower order are rejected, so compare the log-likelihoods of neighbouring
orders as well. A first-order network from build_network() assumes
order 1; when a higher order is selected, build_hon() and
build_mogen() model the longer memory.
Usage
markov_order_test(
data,
max_order = 3L,
n_perm = 500L,
alpha = 0.05,
parallel = FALSE,
n_cores = 2L,
seed = NULL,
dof = c("paths", "observed")
)
## S3 method for class 'net_markov_order'
print(x, ...)
## S3 method for class 'net_markov_order_group'
print(x, ...)
## S3 method for class 'net_markov_order'
summary(object, ...)
## S3 method for class 'net_markov_order'
plot(x, panel = c("both", "ic", "permutation"), combined = TRUE, ...)
Arguments
data |
The sequences: a data frame with one row per sequence and one
column per position, a list of character vectors (one per sequence), a
sequence |
max_order |
The highest order to test, at least 1. Default |
n_perm |
The number of within-context permutations per order, at
least 1. Default |
alpha |
The significance level for the sequential selection,
strictly between 0 and 1. Default |
parallel |
Whether to run the permutations with
|
n_cores |
The number of cores for |
seed |
An integer that makes the permutations reproducible (with
|
dof |
How the AIC and BIC columns count each layer's parameters:
|
x |
For the |
... |
For the |
object |
For the |
panel |
For the |
combined |
For the |
Details
Under the null hypothesis the successors are exchangeable within each
context w, so shuffling s within each w-group keeps
every count the null hypothesis conditions on, with no plug-in estimate
and no refit per permutation. The windows of a sequence overlap, so
this approximates the reference distribution of G^2 rather than
giving it exactly (an exact test would sample whole sequences with the
same counts; Besag & Mondal, 2013). The permutation p-value is
p = \frac{1 + B}{1 + n_{\mathrm{perm}}}
where B is the number of permutations whose G^2 is at least the observed one. An order at which no context holds both two different
extra states and two different successors has no degrees of freedom; it gets
no p-value and counts as not rejected.
The AIC and BIC columns come from the log-likelihood of each order's
fitted chain and its cumulative number of parameters (see dof); BIC
takes the number of observations (observed states) as the sample size.
The deterministic columns agree with tna::markov_order() (tna 1.4.1
or later).
Value
A net_markov_order object. print() shows the data size, the
order each criterion selects and the test table; summary() returns
the test table with the selected orders, alpha and n_perm as
attributes; plot() draws the fit across orders and the permutation
null of each test, and returns a ggplot, a gtable or a list of the two
ggplots (see panel and combined). For a netobject_group, the
result is a net_markov_order_group, a named list of
net_markov_order objects, one per group, whose print() prints
each. The print() methods return their input invisibly. The
net_markov_order's fields:
- optimal_order
The order selected by the sequential permutation test.
- bic_order, aic_order
The orders with the lowest BIC and AIC, shown by
print()andplot()and not used in the selection.- test_table
The test table, one row per order from 0 to
max_order, with columnsorder,loglik,AIC,BIC,df,g2,p_permutation,p_asymptoticandsignificant. The order-0 row hasNAin the test columns (dftosignificant).- permutation_null
The permutation null of
G^2at each order, a list of numeric vectors namedorder_1,order_2, ...- logliks
The log-likelihood of each order, as a named numeric vector (for the AIC and BIC columns only; not used in the test).
- layer_dofs
The parameters added at each order, as a named numeric vector, counted as set by
dof.- dof_method
"paths"or"observed".- transition_matrices
The fitted transition matrices, the order-0 state distribution first.
- states
The observed states.
- n_sequences, n_observations
The number of sequences (after splitting at missing values) and of observed states.
- n_perm, alpha, max_order
The settings used;
max_orderis the highest order actually tested.
Plot panels
- Fit across orders (
"ic") The log-likelihood, AIC and BIC of each order, one facet each, with a dashed line at the order the permutation test selects and a dotted line at the order with the lowest BIC.
- Permutation nulls (
"permutation") The density of the permutation null of
G^2for each order, one facet each, with the observedG^2as a vertical line labelled with its p-value and coloured by whether the test rejects atalpha.
The lines and labels use the Okabe-Ito palette; the null densities are grey.
References
Besag, J., & Mondal, D. (2013). Exact goodness-of-fit tests for Markov chains. Biometrics, 69(2), 488–496. doi:10.1111/biom.12009
Scholtes, I. (2017). When is a network a network? Multi-order graphical model selection in pathways and temporal networks. In Proceedings of the 23rd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (pp. 1037–1046). doi:10.1145/3097983.3098145
Examples
# Is one previous state enough to predict the next one?
res <- markov_order_test(as.data.frame(trajectories),
max_order = 2, n_perm = 19, seed = 1)
res
summary(res)
plot(res)
Describe the stability of each state of a Markov chain
Description
markov_stability() describes how stable each state of a Markov chain
is, one row per state:
its persistence (the probability of staying, P_{ii}), stationary
probability (\pi_i, the long-run share of steps spent in it), mean
recurrence time, sojourn time (the expected number of
consecutive steps in it, 1/(1 - P_{ii})), and the mean of its first
passage times to the other states and of theirs to it, taken from
passage_time(). It reads the same inputs as passage_time() and
analyses a grouped network one network at a time.
Persistence and sojourn time describe staying in a state; the passage
times describe how long it takes to get from it to the other states, or
from them to it. All of them are computed from the estimated transition
matrix. On an irreducible chain, the mean recurrence time is
1/\pi_i. On a reducible chain, recurrence times are computed within
each closed class and are Inf for transient states; passage times to
states not reached with certainty are Inf. The stationary probabilities
are NA when there is more than one closed class, because the stationary
distribution is not unique. chain_structure() identifies the classes;
how far the underlying transition probabilities move under resampling is
shown by bootstrap_network().
Usage
markov_stability(x, normalize = TRUE)
## S3 method for class 'net_markov_stability'
print(x, ...)
## S3 method for class 'net_markov_stability_group'
print(x, ...)
## S3 method for class 'net_markov_stability'
summary(object, ...)
## S3 method for class 'net_markov_stability_group'
summary(object, ...)
## S3 method for class 'net_markov_stability'
plot(
x,
metrics = c("persistence", "stationary_prob", "return_time", "sojourn_time",
"avg_time_to_others", "avg_time_from_others"),
combined = TRUE,
...
)
## S3 method for class 'net_markov_stability_group'
plot(
x,
metrics = c("persistence", "stationary_prob", "return_time", "sojourn_time",
"avg_time_to_others", "avg_time_from_others"),
...
)
Arguments
x |
The chain, as in |
normalize |
Whether to rescale rows that do not sum to 1 so that
they do, with a warning, as for a |
... |
Not used ( |
object |
For the |
metrics |
For the |
combined |
For |
Details
Sojourn time is the expected number of consecutive steps spent
in a state before leaving it, 1/(1-P_{ii}), the mean of a geometric
distribution. A state with persistence = 1 never leaves and has
sojourn_time = Inf.
avg_time_to_others is the mean passage time from the state to each other state: a high value means the chain takes long to get anywhere else from it.
avg_time_from_others is the mean passage time from each other state to this one: a low value means the state is reached quickly from elsewhere.
Value
A net_markov_stability object; for a netobject_group, a
net_markov_stability_group, a named list holding one such object per
group. print() names the attractor (the state with the lowest mean
passage time from the other states) and the stickiest state (the
longest sojourn time) in its header, shows the per-state table and
returns its input invisibly. summary() returns the per-state table as a data frame and
prints nothing. plot() returns a ggplot with one panel of bars per metric and
the states ordered by stationary probability; with combined = FALSE,
invisibly, a list of one-panel plots named by metric. For a group,
plot() draws one panel per metric with one row per state and one
point per group (told apart by colour and shape) joined by a line, the
states ordered by their mean stationary probability; more than 81
groups (9 colours times 9 shapes) raise an error of class
nestimate_bad_input. A net_markov_stability holds:
- stability
The per-state table, one row per state, with the columns
state,persistence(P_{ii}),stationary_prob(\pi_i),return_time(the mean recurrence time),sojourn_time(1/(1-P_{ii})),avg_time_to_others(the mean first passage time from the state to the others) andavg_time_from_others(the mean first passage time from the others to the state).persistenceandstationary_probare rounded to 4 decimals, the times to 2.- mpt
The
net_mptfrompassage_time()the times come from.
For summary() of a net_markov_stability_group: a data frame
with one row per group and state, the group column followed by the
columns of the single-network stability table.
References
Kemeny, J.G. and Snell, J.L. (1976). Finite Markov Chains. Springer-Verlag.
See Also
Examples
net <- build_network(as.data.frame(trajectories), method = "relative")
ms <- markov_stability(net)
print(ms)
plot(ms)
Extract the transitions of a MOGen model
Description
mogen_transitions() returns the transitions of a fitted build_mogen()
model at one order, one row per path, most frequent first, with the
path written out in arrow notation, its observed count and its
transition probability. At order k each edge of the De Bruijn graph is a
path of k + 1 states: at order 2, the edge from node "AI -> FAIL" to
node "FAIL -> SOLVE" is the path AI -> FAIL -> SOLVE, read as the
probability of SOLVE after the context AI -> FAIL.
A probability is the share of its context's observations that moved to
that state, so in a context seen a few times it rests on those few
observations: read it with its count, and use min_count to leave
rare transitions out.
Usage
mogen_transitions(x, order = NULL, min_count = 1L)
Arguments
x |
A |
order |
The order whose transitions are returned, a whole number
from 1 to the highest order fitted; a non-integer value is an error,
not truncated. Default |
min_count |
The smallest observed count a transition needs to be
listed. Default |
Value
A data frame with one row per listed transition, sorted by
count (descending), with columns:
- path
The full sequence of states, such as
"AI -> FAIL -> SOLVE".- count
How often the transition was observed.
- probability
The transition probability P(to | from), rounded to 4 decimal places.
- from
The context: the k states the transition starts from.
- to
The next state.
When no transition reaches min_count, a data frame with the same
columns and no rows.
Examples
seqs <- list(c("A","B","C","D"), c("A","B","C","A"), c("B","C","D","A"))
mg <- build_mogen(seqs, max_order = 2)
mogen_transitions(mg, order = 1)
trajs <- list(c("A","B","C","D"), c("A","B","D","C"),
c("B","C","D","A"), c("C","D","A","B"))
m <- build_mogen(trajs, max_order = 3)
mogen_transitions(m, order = 1)
Test and draw the association of two categorical variables
Description
mosaic_analysis() tests the association between two categorical columns
of a data frame and draws it as a mosaic. It builds their contingency
table, drops sparse categories (fewer than min_count rows), runs a
Pearson chi-square test (or Fisher's exact test), computes Cramer's V
with an effect-size label, and draws a flat ggplot2 mosaic in which tile
area is the cell count and the fill is the cell's standardised
residual. The per-cell results come as a data frame, one row per cell.
The p-value tests the null hypothesis that the two variables are
independent; with large samples almost any departure is significant, so
read Cramer's V for the size of the association. The label follows
Cohen's (1988) thresholds for the table's degrees of freedom,
min(rows, columns) - 1: 0.10 / 0.30 / 0.50 for small /
medium / large at 1, 0.07 / 0.21 / 0.35 at 2, 0.06 / 0.17 / 0.29 at 3,
and 0.05 / 0.15 / 0.25 above (Cohen's w divided by the square root of the
degrees of freedom); a V below the small threshold is labelled
"negligible". The residuals are chisq.test()'s standardised
residuals, roughly standard normal under independence, so one beyond
about +-2 marks a cell that holds more (or fewer) rows than independence
predicts; with many cells, some pass that line by chance.
Usage
mosaic_analysis(
data,
var1,
var2,
min_count = 10L,
test = c("chisq", "fisher"),
percentage_base = c("total", "row", "column"),
tile_label = c("count", "percent", "residual", "category", "none"),
title = "",
...,
nested = FALSE,
nested_method = c("rao_scott", "donner_klar", "cmh", "gee", "glmm"),
actor = NULL,
report = FALSE
)
## S3 method for class 'mosaic_analysis'
plot(x, ...)
## S3 method for class 'mosaic_analysis'
print(x, ...)
## S3 method for class 'mosaic_analysis'
summary(object, ...)
Arguments
data |
A data frame holding the two variables. Rows missing either
of them (or an |
var1 |
The name of the first variable, drawn as the mosaic's columns (column width is its marginal share). |
var2 |
The name of the second variable, stacked within each column. |
min_count |
The smallest number of rows a category must have to be
kept. Categories of either variable with fewer rows in the full table
are dropped, in one pass, before the test. Default |
test |
The test reported: |
percentage_base |
What the |
tile_label |
What to print inside each tile: |
title |
The plot title. Default |
... |
Further styling for the flat mosaic:
Column labels turn
vertical when there are more than 6 columns; |
nested |
Whether the rows are nested in actors and the test should
allow for it. Default |
nested_method |
With |
actor |
With |
report |
Whether to report the test: |
x |
For the |
object |
For the |
Value
A mosaic_analysis object. print() shows the sample size, the
test, Cramer's V with its label and the dropped categories, and returns
the object invisibly; summary() returns the per-cell data frame (the
counts table below) with the one-row test summary attached as the
attribute "stats"; plot() draws the mosaic on the active device,
with new styling if given, and returns the ggplot invisibly. The
object is a list with:
- plot
The flat mosaic, a
ggplot. Building the object does not draw it.- counts
A data frame with one row per (
var1,var2) cell: the two variables (named after them),observed,expected,residual(the standardised residual, or the nested test's residual,NAwhere it is undefined and drawn at 0) andpct(onpercentage_base);expectedandresidualare rounded to 3 decimals,pctto 2.- stats
A one-row data frame:
test,statistic,df,df2,p_value,cramers_v,effect_size,n,clusters,design_effectandicc, rounded (statisticandcramers_vto 3 decimals,p_valueto 4 significant digits).statisticanddfareNAfor Fisher's test.df2(the denominator degrees of freedom of the Rao-Scott F),clusters,design_effectandiccareNAwhere the test has none.- test
The
htestobject of the test reported;NULLfor a nested test.- actor
The
actorcolumn names, orNULL.- cramers_v, effect_size
Cramer's V, unrounded, and its label. V is computed from Pearson's chi-square without Yates' continuity correction, as Cramer defined it, so a perfect 2 x 2 association gives 1; the 2 x 2 test reported keeps the correction.
- table
The filtered contingency table.
- removed
The dropped categories, as a list with
var1andvar2.- n_original, n_filtered
The number of complete rows before and after the sparse categories are dropped.
- vars
The two variable names, as
c(var1 = , var2 = ).- plot_parts, plot_args
The residual matrix, the table, the test line drawn as the subtitle with
report = TRUE, and the styling, kept soplot()can redraw without testing again.
Nested data
Pearson's test treats every row as an independent observation. When rows
are nested in actors (events within students, students within classes),
rows of one actor resemble each other and the test is too liberal. Set
nested = TRUE and name the actor column(s) in actor (as in
permutation()). The test is then nested_method, one of five that
allow for the nesting; each gives a test and its own residual per cell,
which fills the mosaic.
"rao_scott"(default)Rao-Scott second-order corrected chi-square, reported as an F statistic on fractional degrees of freedom (the default of
survey::svychisq(), which it reproduces for an unweighted cluster sample). Works for any cluster sizes and when both variables vary within clusters.design_effectis the mean generalised design effect; 1 means the clustering costs nothing. Residual: the standardised residual divided by the square root of the cell's design effect (cluster-robust over simple-random-sampling variance ofp_ij - p_i. p_.j); with one row per cluster it ischisq.test()'s, and it isNAwhere the cell's design effect is zero. With empty cells the design effects are those of the estimable contrasts. The test is liberal with few actors when one variable is constant within actors: in simulations of 3 x 4 tables its type I error at alpha = 0.05 was 0.22 with 10 actors, 0.10 with 30 and 0.06 with 100."donner_klar"Pearson's chi-square divided, group by group, by the inflation factor
1 + (m - 1) * rho(its weighted form for unequal cluster sizes), whererhois the ANOVA intracluster correlation ofvar2, pooled within the levels of the other variable. For designs where one variable is constant within each cluster, as in a cluster-randomised trial; otherwise an error is raised.iccisrho; a negative estimate is reported and used as 0. Residual: the standardised residual divided by the square root of its group's factor."cmh"Generalised Cochran-Mantel-Haenszel test with each cluster as a stratum: is there an association within clusters? Suits a few clusters with enough rows each; both variables must vary within clusters, and clusters with fewer than two rows are left out (
clusterscounts those that inform the test). Residual: summed observed minus expected over the square root of the summed hypergeometric variances. This tests conditional association, whereas Rao-Scott and GEE test marginal association; the null hypotheses can differ. Stratification does not correct arbitrary serial dependence among observations within an actor."gee"Marginal model for
var2givenvar1with an identity link and independence working correlation; Wald chi-square with the cluster-robust (sandwich) covariance for equal distributions ofvar2acrossvar1, on(rows - 1) (columns - 1)degrees of freedom. When the covariance has lower rank (fewer actors than degrees of freedom, or cells that never occur) the test would depend on the order of rows and columns, and an error of classnestimate_bad_inputis raised. The Wald test is liberal unless the actors are many relative to the degrees of freedom: in simulations of 3 x 4 tables its type I error at alpha = 0.05 was 0.28 with 30 actors and 0.11 with 100. Residual: the share ofvar2within the level ofvar1minus the pooled share, over its cluster-robust standard error."glmm"Log-linear Poisson mixed model of the cluster-by-cell counts with random intercepts for cluster-by-
var1and cluster-by-var2at every level ofactor, so several columns give nested random effects (outermost first); Wald chi-square on the interaction. Fitted bylme4::glmer(nAGQ = 0), a faster, less exact approximation than the default Laplace fit; needs lme4, and a failed fit raises an error of classnestimate_bad_input. With an empty cell the Wald test loses power (its interaction term runs to minus infinity). Residual: observed minus expected count under independence, over its cluster-robust standard error (the GLMM supplies the test, the residual is model-free). With several actor levels, this standard error clusters at the outermost level; it is undefined with fewer than two outer actors. With about 10 actors this standard error is small and 7 to 8% of null cells pass 1.96.
With several actor columns, the four other tests use the outermost
(the first), which carries the dependence of every level below it.
Cramer's V is the pooled-table effect
size whatever the test: the clustering changes the uncertainty, not the
size of the association.
Methods
-
plot.mosaic_analysis()redraws the flat mosaic from the stored contingency table and residuals, so the styling can change without the test being run again. Any flat-mosaic styling argument (tile_label,pct_base,col_label_side,legend_size, ...) can be overridden through....
References
Cohen, J. (1988). Statistical power analysis for the behavioral sciences (2nd ed.). Lawrence Erlbaum.
Rao, J. N. K., & Scott, A. J. (1984). On chi-squared tests for multiway contingency tables with cell proportions estimated from survey data. The Annals of Statistics, 12(1), 46–60. doi:10.1214/aos/1176346391
Donner, A., & Klar, N. (1994). Methods for comparing event rates in intervention studies when the unit of allocation is a cluster. American Journal of Epidemiology, 140(3), 279–289. doi:10.1093/oxfordjournals.aje.a117247
Landis, J. R., Heyman, E. R., & Koch, G. G. (1978). Average partial association in three-way contingency tables: A review and discussion of alternative tests. International Statistical Review, 46(3), 237–254. doi:10.2307/1402373
Liang, K.-Y., & Zeger, S. L. (1986). Longitudinal data analysis using generalized linear models. Biometrika, 73(1), 13–22. doi:10.1093/biomet/73.1.13
Agresti, A. (2013). Categorical data analysis (3rd ed.), chapter 13. Wiley.
See Also
mosaic_plot for the network/table mosaic (which also
accepts style = "flat"); mosaic_test for every
test, clustered or not, side by side in one table.
Examples
data(group_regulation_long, package = "Nestimate")
res <- mosaic_analysis(group_regulation_long, "Course", "Action",
min_count = 20)
res
head(summary(res))
plot(res, tile_label = "percent")
# Actions are nested in students: Rao-Scott test by student
nested <- mosaic_analysis(group_regulation_long, "Course", "Action",
nested = TRUE, actor = "Actor")
nested
Draw a mosaic plot of transition or co-occurrence counts
Description
mosaic_plot() draws a mosaic display of a contingency table and fills
each tile with its standardised residual under independence: blue tiles
hold more cases than independence predicts, red tiles fewer. It reads the
transition or co-occurrence counts of a netobject or htna network, the
state counts of each group of a netobject_group, the cluster-level or
per-cluster counts of an mcml, or a table or count matrix given
directly. A data frame in long form is drawn as a plain marimekko of
shares instead, coloured by the stacked variable (or the fill
column), without residuals.
In a network's mosaic each column is a target state, its width
proportional to the transitions into it, and its segments are the source
states, stacked in proportion to their share of those transitions. For a
netobject_group the columns are the groups and the segments the states,
counted from each group's sequences, so the mosaic shows how the state
mix differs between groups. For a table or matrix, its rows are the
columns of the mosaic and its columns the stacked segments. An htna
network has its states ordered by actor, with each state's label set in
bold in its actor's colour.
The residuals describe where the counts depart from independence; they
are not tests of single cells. The default residuals treat every
transition or state as an independent draw, but those of one sequence
(or one student, or one team) are not. With nested = TRUE the
residuals allow for that nesting; report = TRUE adds the overall test
as the subtitle and prints it; see Nested data. To test edges or group
differences, use permutation(); for a chi-square or Fisher test with
Cramér's V on two variables of a data frame, use
mosaic_analysis().
Usage
mosaic_plot(x, ...)
## Default S3 method:
mosaic_plot(x, ...)
## S3 method for class 'netobject'
mosaic_plot(
x,
xlab = NULL,
ylab = NULL,
range = NULL,
top_angle = NULL,
left_angle = NULL,
residuals = c("permutation", "asymptotic"),
n_perm = 500L,
seed = NULL,
values = FALSE,
style = c("classic", "flat"),
...,
nested = FALSE,
nested_method = c("rao_scott", "donner_klar", "cmh", "gee", "glmm"),
actor = NULL,
report = FALSE
)
## S3 method for class 'htna'
mosaic_plot(
x,
xlab = NULL,
ylab = NULL,
range = NULL,
top_angle = NULL,
left_angle = NULL,
residuals = c("permutation", "asymptotic"),
n_perm = 500L,
seed = NULL,
values = FALSE,
style = c("classic", "flat"),
...,
nested = FALSE,
nested_method = c("rao_scott", "donner_klar", "cmh", "gee", "glmm"),
actor = NULL,
report = FALSE
)
## S3 method for class 'mcml'
mosaic_plot(
x,
level = c("macro", "clusters"),
xlab = NULL,
ylab = NULL,
range = NULL,
top_angle = NULL,
left_angle = NULL,
residuals = c("permutation", "asymptotic"),
n_perm = 500L,
seed = NULL,
ncol = 2L,
values = FALSE,
style = c("classic", "flat"),
...
)
## S3 method for class 'netobject_group'
mosaic_plot(
x,
xlab = NULL,
ylab = NULL,
range = NULL,
top_angle = NULL,
left_angle = NULL,
residuals = c("permutation", "asymptotic"),
n_perm = 500L,
seed = NULL,
ncol = 2L,
values = FALSE,
style = c("classic", "flat"),
...,
nested = FALSE,
nested_method = c("rao_scott", "donner_klar", "cmh", "gee", "glmm"),
actor = NULL,
report = FALSE
)
## S3 method for class 'table'
mosaic_plot(
x,
xlab = "Row",
ylab = "Column",
range = NULL,
top_angle = NULL,
left_angle = NULL,
residuals = c("permutation", "asymptotic"),
n_perm = 500L,
seed = NULL,
values = FALSE,
style = c("classic", "flat"),
...,
nested = FALSE,
nested_method = c("rao_scott", "donner_klar", "cmh", "gee", "glmm"),
report = FALSE
)
## S3 method for class 'matrix'
mosaic_plot(x, ...)
## S3 method for class 'array'
mosaic_plot(x, ...)
## S3 method for class 'data.frame'
mosaic_plot(
x,
x_var,
y_var,
weight,
fill = "y",
colors = NULL,
show_labels = TRUE,
label_size = 3.5,
xlab = NULL,
ylab = NULL,
...
)
Arguments
x |
The object to draw: a |
... |
With |
xlab, ylab |
Axis titles. The network and |
range |
The lower and upper limits of the residual colour scale, two
increasing numbers; residuals beyond them take the end colours. Default
|
top_angle, left_angle |
Rotation, in degrees, of the column labels on
top and the segment labels on the left. Default |
residuals |
How the standardised residuals are computed.
|
n_perm |
The number of shuffles for |
seed |
A seed for the shuffles, so the residuals repeat exactly. The
session's own random stream is left as it was. Default |
values |
Whether to print each tile's residual (one decimal) inside
it. Default |
style |
|
nested |
Whether the counts are nested in actors (transitions in
sequences, sequences in students or teams) and the residuals should
allow for it. Default |
nested_method |
With |
actor |
With |
report |
Whether to report the overall test: |
level |
For an |
ncol |
For an |
x_var, y_var, weight |
For a data frame: the column whose levels form
the mosaic's columns (each as wide as its total |
fill |
For a data frame: |
colors |
For a data frame with |
show_labels, label_size |
For a data frame: whether to print each
segment's percentage inside it (default |
Details
A mosaic needs counts, never probabilities. A network is drawn from the
transition counts stored with it at estimation; failing that from its
weights, when its method counts (such as "frequency") and they are not
scaled, thresholded or weighted; and failing that from first-order
transitions recounted from its sequence data. A network that records no
method is drawn from its weights if they are whole numbers. A
netobject_group is counted from each group's sequences, or
from the column sums of its weights when they are counts. A single
network with none of these, such as an association network (cor,
pcor, glasso, ising, mgm), raises an error.
A co-occurrence network (method = "co_occurrence") is undirected: it
stores each unordered pair of positions in both mirrored cells and the
same-state pairs once on the diagonal, so its matrix is not a table of
row-by-column counts. The mosaic draws its table of pairs instead, each
pair counted once and split equally between its two mirrored cells (so a
cell can hold a half; Newman, 2003), and the residuals compare it with
random pairing of the pair ends, which keeps how often each state ends a
pair: "permutation" re-pairs the ends at random n_perm times, and
"asymptotic" gives each unordered pair's multinomial residual under
that null, as for genotypes under Hardy-Weinberg proportions (Guo &
Thompson, 1992). The pairs of a sequence share its positions, so they
are not independent counts, and report = TRUE or nested = TRUE on a
co-occurrence network raises an error of class
nestimate_mosaic_undirected. So does any mosaic of an undirected
network whose diagonal holds each state's own occurrences rather than
pairs: a windowed or one-hot co-occurrence network, "wtna_cooccurrence"
and cooccurrence().
A netobject_group
must hold sequence networks: the group method counts whatever its
networks' data hold, so a group of association networks is drawn
without an error, each distinct numeric value counted as a state. An
mcml is counted the same way as a network, layer by layer; a cluster
with a single state has no table to draw: when it holds self-transitions
it is left out of the per-cluster figure with a warning, and when it holds
no transition at all the call stops with an error. When a row or
column of the table is empty, its cells have no asymptotic residual and
are drawn at 0; the other cells keep theirs. The geometry and the asymptotic
residuals follow tna::plot_mosaic(); the function has its own name so
the two packages can be attached together.
Value
A ggplot object, one rectangle per cell (empty cells are left
out of the flat and data-frame mosaics), filled by the standardised
residual (by category for a data frame). Print it to draw
it, or add ggplot2 layers and themes. An mcml with
level = "clusters" gives one faceted ggplot with a panel per
cluster and one shared fill scale. An object of an unsupported class
raises an error.
Nested data
A network's counts are summed over sequences. With nested = TRUE
the counts are taken sequence by sequence (as the network counted them),
summed within the actors named by actor (each sequence on its own
by default), and nested_method reads the table of each actor.
With report = TRUE the subtitle names the test, its statistic, degrees
of freedom and p-value, the number of actors, and the design effect or
intracluster correlation where the method gives one. For a network,
the source state is treated as the predictor and the target as the
response; for a netobject_group, the group is the predictor and the
state the response. The nested_method choices:
"rao_scott"(default)Rao-Scott second-order corrected chi-square, an F statistic on fractional degrees of freedom (as
survey::svychisq()); any cluster sizes. Residual: the standardised residual divided by the square root of the cell's design effect. With one observation per actor it equals the default asymptotic residual, so it corrects only as much as the data are clustered."donner_klar"Pearson's chi-square divided by the cluster-size inflation factor
1 + (m - 1) * rho. Needs one variable that is constant within every cluster, as the group of anetobject_group; a single network raises an error."cmh"Generalised Cochran-Mantel-Haenszel test with each cluster as a stratum; both variables must vary within clusters, so a
netobject_groupraises an error."gee"Wald chi-square of a marginal model (identity link, independence working correlation) with the cluster-robust covariance; refused when that covariance is rank-deficient, and liberal unless the actors are many relative to the degrees of freedom. Residual: conditional minus pooled share, over its cluster-robust standard error.
"glmm"Wald chi-square on the interaction of a log-linear Poisson mixed model with cluster random effects at every level of
actor; needs lme4. Residual: observed minus expected count under independence, over its cluster-robust standard error.
The methods are described in full under Nested data in
mosaic_analysis(). nested = TRUE needs per-sequence counts: a
network built with method = "relative" or "frequency" that keeps its
sequence data, or a netobject_group whose groups keep theirs. Other
networks, and per-sequence counts that do not add up to the drawn table,
raise an error of class nestimate_bad_input; a co-occurrence network
raises one of class nestimate_mosaic_undirected (see Details). An
mcml takes no nested. A table or
matrix (or a plain array) takes it as a three-way table, rows x columns x actors (e.g.
table(var1, var2, actor)); the mosaic draws the table summed over
actors. A three-way table without nested = TRUE, or a two-way table
with it, raises an error.
Residuals a method leaves undefined are drawn at 0. For the tests as a
table, all methods side by side, use mosaic_test().
References
Friendly, M. (1994). Mosaic displays for multi-way contingency tables. Journal of the American Statistical Association, 89(425), 190–200. doi:10.1080/01621459.1994.10476460
Guo, S. W., & Thompson, E. A. (1992). Performing the exact test of Hardy-Weinberg proportion for multiple alleles. Biometrics, 48(2), 361–372. doi:10.2307/2532296
Newman, M. E. J. (2003). Mixing patterns in networks. Physical Review E, 67(2), 026126. doi:10.1103/PhysRevE.67.026126
Rao, J. N. K., & Scott, A. J. (1984). On chi-squared tests for multiway contingency tables with cell proportions estimated from survey data. The Annals of Statistics, 12(1), 46–60. doi:10.1214/aos/1176346391
Donner, A., & Klar, N. (1994). Methods for comparing event rates in intervention studies when the unit of allocation is a cluster. American Journal of Epidemiology, 140(3), 279–289. doi:10.1093/oxfordjournals.aje.a117247
Landis, J. R., Heyman, E. R., & Koch, G. G. (1978). Average partial association in three-way contingency tables: A review and discussion of alternative tests. International Statistical Review, 46(3), 237–254. doi:10.2307/1402373
Liang, K.-Y., & Zeger, S. L. (1986). Longitudinal data analysis using generalized linear models. Biometrika, 73(1), 13–22. doi:10.1093/biomet/73.1.13
Examples
data(group_regulation_long, package = "Nestimate")
net <- build_network(group_regulation_long, method = "frequency",
format = "long", actor = "Actor", action = "Action",
order = "Time")
mosaic_plot(net, seed = 1)
# Transitions are nested in students' sequences, students in teams:
mosaic_plot(net, nested = TRUE, actor = "Group", report = TRUE)
# A tidy data frame: columns by group, segments by state
df <- data.frame(
group = rep(c("A", "B", "C"), each = 3),
state = rep(c("s1", "s2", "s3"), 3),
count = c(10, 5, 2, 7, 8, 3, 4, 6, 12)
)
mosaic_plot(df, x_var = "group", y_var = "state", weight = "count")
Test the association of a mosaic with and without clustering
Description
mosaic_test() runs the tests behind mosaic_plot() and
mosaic_analysis() and returns their results as a data frame. Give it
the same object you would draw: a network, a netobject_group, a
three-way table, or a data frame with two variables. By default it runs
Pearson's chi-square, which treats every count as independent, next to
the five tests that allow for counts nested in actors (sequences,
students, teams), so the table shows what the nesting changes.
The tests are those of Nested data in mosaic_analysis():
"rao_scott" (Rao-Scott corrected F), "donner_klar" (Pearson divided
by the cluster-size inflation factor), "cmh" (generalised
Cochran-Mantel-Haenszel with each actor as a stratum), "gee" (Wald
test of a marginal model with cluster-robust covariance) and "glmm"
(Wald test of a log-linear mixed model, needs lme4). "chisq" is
Pearson's test on the pooled table. As in the mosaics, a network's
source state and a group are the predictors.
Not every test fits every design: Donner-Klar needs one variable that is
constant within actors (the group of a netobject_group), and CMH needs
both to vary within actors (the states of a network). When several
methods are asked for, a test that cannot run on the design gives a row
of NA with the reason in note; asked for alone, it raises the error.
Usage
mosaic_test(x, ...)
## Default S3 method:
mosaic_test(x, ...)
## S3 method for class 'netobject'
mosaic_test(
x,
method = c("chisq", "rao_scott", "donner_klar", "cmh", "gee", "glmm"),
actor = NULL,
level = c("test", "cells"),
...
)
## S3 method for class 'htna'
mosaic_test(
x,
method = c("chisq", "rao_scott", "donner_klar", "cmh", "gee", "glmm"),
actor = NULL,
level = c("test", "cells"),
...
)
## S3 method for class 'netobject_group'
mosaic_test(
x,
method = c("chisq", "rao_scott", "donner_klar", "cmh", "gee", "glmm"),
actor = NULL,
level = c("test", "cells"),
...
)
## S3 method for class 'array'
mosaic_test(x, ...)
## S3 method for class 'table'
mosaic_test(
x,
method = c("chisq", "rao_scott", "donner_klar", "cmh", "gee", "glmm"),
level = c("test", "cells"),
...
)
## S3 method for class 'data.frame'
mosaic_test(
x,
var1,
var2,
actor,
method = c("chisq", "rao_scott", "donner_klar", "cmh", "gee", "glmm"),
level = c("test", "cells"),
...
)
Arguments
x |
A |
... |
Not used; a name given here raises an error of class
|
method |
The tests to run, any of |
actor |
The actor column(s), as in |
level |
|
var1, var2 |
For a data frame: the names of the two variables;
|
Value
A data frame. With level = "test", one row per test: method,
test (its name), statistic (F for Rao-Scott, chi-square otherwise),
df, df2 (the Rao-Scott denominator degrees of freedom), p_value,
n (counts in the table), clusters (actors the test used),
design_effect (Rao-Scott's mean generalised design effect, or
Donner-Klar's mean inflation factor), icc (Donner-Klar's
intracluster correlation) and note (why a test did not run, the caution on the GEE Wald test, else
NA). With level = "cells", one row per cell and test: method,
the two variables (from/to for a network, group/state for a
group, the variable names for a data frame, row/column for a
table), observed and residual (the residual the mosaic draws for
that method; NA where undefined). An unsupported input raises an
error of class nestimate_bad_input.
References
Rao, J. N. K., & Scott, A. J. (1984). On chi-squared tests for multiway contingency tables with cell proportions estimated from survey data. The Annals of Statistics, 12(1), 46–60. doi:10.1214/aos/1176346391
Donner, A., & Klar, N. (1994). Methods for comparing event rates in intervention studies when the unit of allocation is a cluster. American Journal of Epidemiology, 140(3), 279–289. doi:10.1093/oxfordjournals.aje.a117247
Landis, J. R., Heyman, E. R., & Koch, G. G. (1978). Average partial association in three-way contingency tables: A review and discussion of alternative tests. International Statistical Review, 46(3), 237–254. doi:10.2307/1402373
Liang, K.-Y., & Zeger, S. L. (1986). Longitudinal data analysis using generalized linear models. Biometrika, 73(1), 13–22. doi:10.1093/biomet/73.1.13
See Also
mosaic_plot(), mosaic_analysis()
Examples
data(group_regulation_long, package = "Nestimate")
net <- build_network(group_regulation_long, method = "frequency",
format = "long", actor = "Actor", action = "Action",
order = "Time")
mosaic_test(net, method = c("chisq", "rao_scott"), actor = "Group")
# Several tests, sequences nested in teams (the default runs them all,
# the mixed model included)
mosaic_test(net, method = c("rao_scott", "donner_klar", "cmh", "gee"),
actor = "Group")
# Cell residuals of one test
head(mosaic_test(net, method = "rao_scott", actor = "Group",
level = "cells"))
Compare two networks with the network comparison test
Description
nct() tests whether two networks estimated from two samples of the same
variables differ, at the three levels of van Borkulo et al. (2022):
network structure (statistic M, the largest absolute edge
difference), global strength (statistic S, the difference in the
summed absolute edge weights, or with abs = FALSE in the summed signed
weights, the global expected influence) and individual edges
(statistic E, the absolute difference of each edge). Each network is an
EBIC graphical lasso network of the Pearson correlations, and each
p-value comes from re-estimating both networks on permuted group labels
(within-pair swaps with paired = TRUE).
A p-value counts the permutations whose statistic is at least the
observed one, with the observed split added:
(sum(perm >= observed) + 1) / (iter + 1), so the smallest attainable
value is 1 / (iter + 1). A non-significant test does not
show that the networks are equal; with small samples the test has little
power (van Borkulo et al. 2022). The edge tests are many tests at once;
set p_adjust before reading single edges.
Both networks are regularised estimates, so check how stable each one is
with boot_glasso().
Usage
nct(
data1,
data2,
iter = 1000L,
gamma = 0.5,
paired = FALSE,
abs = TRUE,
weighted = TRUE,
p_adjust = "none",
na_method = c("pairwise", "listwise")
)
## S3 method for class 'net_nct'
print(x, n = 6L, ...)
## S3 method for class 'net_nct'
summary(object, table = c("tests", "edges"), ...)
## S3 method for class 'net_nct'
as.data.frame(x, row.names = NULL, optional = FALSE, ...)
Arguments
data1 |
The observations of group 1: a numeric matrix or data frame, one row per observation. Non-numeric columns are dropped; at least two numeric variables and three rows are needed. |
data2 |
The observations of group 2, with the same variables as
|
iter |
The number of permutations, a whole number of at least 1.
Default |
gamma |
The EBIC tuning parameter of the glasso, a non-negative
number; larger values give sparser networks. Default |
paired |
Whether row |
abs |
Whether global strength sums the absolute edge weights. With
|
weighted |
Whether the tests compare the weighted networks. With
|
p_adjust |
The multiplicity correction for the per-edge p-values,
any method of |
na_method |
How missing values are handled. |
x |
For the |
n |
For the |
... |
For the |
object |
For the |
table |
For the |
row.names, optional |
For the |
Details
nct() follows NetworkComparisonTest::NCT() with its defaults
abs = TRUE, weighted = TRUE and paired = FALSE. The network
estimator is EBIC-selected glasso (psychnets::ebic_glasso()) applied to
a Pearson correlation matrix made positive definite with
Matrix::nearPD() (NCT's NCT_estimator_GGM default). Under the same
seed both functions permute the same rows, so the permutation p-values
agree; the glasso solver is not the Fortran one NCT wraps, so the test
statistics agree to independent-solver precision (of the order of
1e-4) rather than bit for bit. The Matrix package (in Suggests)
must be installed.
The two groups must hold the same variables in the same order;
non-numeric columns, such as an id or a group label, are dropped first.
Infinite values are refused; use finite observations or NA for missing
data.
A variable without variation in a group, or in a permuted split (a rare
binary item can be constant in a split), enters that network as an
isolated node. The statistic is then defined on every split, so the
permutation test stays exact. A constant variable in an observed group
raises a warning of class nestimate_constant_variable.
Malformed iter, gamma, paired, abs, weighted or data raise an
error of class nestimate_bad_input.
Value
A net_nct object. print() reports the three tests, each
group's global strength and the edges, largest difference first, and
returns the object invisibly; summary() returns the M and S tests as
a data frame with one row per test. The object's fields:
- nw1, nw2
The estimated weighted adjacency matrices of the two groups (binarised with
weighted = FALSE).- structure
The network-structure test (statistic M, the largest absolute edge difference):
observed,perm(the statistic in each permutation) andp_value.- strength
The global-strength test (statistic S): the same, plus
by_group, each network's global strength (NCT'sglstrinv.sep).- E
The per-edge tests:
observedandp_valuehold one value per node pair (the upper triangle),permis aniterby node-pair matrix, andedge_namesis a data frame with the columnsfromandtonaming each node pair.- n_iter
The number of permutations.
- groups
The display names of the two groups: the argument names when they are plain variables, otherwise
"group 1"and"group 2".- n
The rows used in each group.
- paired
Whether a paired test was used.
- params
The settings used:
gamma,abs,weighted,p_adjustandna_method.
The letters follow van Borkulo et al. (2022) and
NetworkComparisonTest. Before Nestimate 0.9.27 the fields M and S
held the global-strength and network-structure tests the other way
round; reading them now raises an error of class nestimate_renamed.
For the summary() method: a data frame with one row per global
test and the columns test ("network structure", and
"global strength", or "global expected influence" when
abs = FALSE), statistic ("M", "S"), observed, p_value and
significant (p_value < 0.05, a fixed level). With
table = "edges" (and the as.data.frame() method), one row per node
pair, with the columns from, to,
weight_1 and weight_2 (the edge in each group's network),
difference (statistic E), p_value and significant
(p_value < 0.05).
References
van Borkulo, C. D., van Bork, R., Boschloo, L., Kossakowski, J. J., Tio, P., Schoevers, R. A., Borsboom, D., & Waldorp, L. J. (2022). Comparing network structures on three aspects: A permutation test. Psychological Methods. doi:10.1037/met0000476
Examples
set.seed(1)
x1 <- matrix(rnorm(100 * 4), 100, 4)
x2 <- matrix(rnorm(100 * 4), 100, 4)
colnames(x1) <- colnames(x2) <- paste0("V", 1:4)
# iter = 20 keeps the example fast; a real analysis uses 1000 or more.
res <- nct(x1, x2, iter = 20)
res
summary(res)
Aggregate edge weights into one value
Description
net_aggregate_weights() reduces a vector of edge weights to one number:
their sum, mean, median, maximum, minimum, product, density or geometric
mean. Missing and zero weights are removed first, so every method works on
the edges that are present. cluster_summary() and build_mcml() use it to
combine the edges between two clusters into one cluster-level weight.
Usage
net_aggregate_weights(w, method = "sum", n_possible = NULL)
Arguments
w |
The edge weights, a numeric vector. |
method |
How to combine the weights: |
n_possible |
For |
Details
"sum", "prod", "min", "max", "mean" and "median" mean what
they mean in igraph's edge.attr.comb argument.
Value
A single number: the chosen aggregate of the non-zero, non-missing
weights, or 0 when none remain.
Examples
w <- c(0.5, 0.8, 0.3, 0.9)
net_aggregate_weights(w, "sum") # 2.5
net_aggregate_weights(w, "mean") # 0.625
net_aggregate_weights(w, "max") # 0.9
net_aggregate_weights(w, "density", n_possible = 9) # 2.5 / 9
Compute centrality measures for a network
Description
net_centrality() scores how central each node is in a network, for one
or more measures, and returns one row per node. Strength sums a node's
edge weights (incoming or outgoing); closeness and betweenness read the
shortest paths between nodes, where a heavier edge is a shorter step;
diffusion counts the weighted walks that start at a node; and clustering
measures how strongly a node's neighbours are tied to each other. It
takes a single network or a group of them (a netobject_group, the
clusters of an mcml), scoring each separately.
Centralities describe the estimated network, not the population it was
estimated from. Rankings built on a few weak edges change from sample to
sample: check them with centrality_stability() before reporting which
node is most central.
Usage
net_centrality(
x,
measures = NULL,
loops = FALSE,
normalize = FALSE,
invert = TRUE,
normalize_diffusion = TRUE,
centrality_fn = NULL,
format = c("long", "wide"),
...
)
## S3 method for class 'net_centrality'
print(x, n = 20L, digits = 2L, ...)
## S3 method for class 'net_centrality'
summary(object, ...)
## S3 method for class 'net_centrality_group'
print(x, n = 20L, digits = 2L, ...)
## S3 method for class 'net_centrality_group'
summary(object, ...)
## S3 method for class 'net_centrality_group'
x[i, j, ...]
## S3 method for class 'net_centrality'
x[i, j, ...]
## S3 method for class 'net_centrality'
plot(
x,
reorder = TRUE,
ncol = 3L,
type = c("bar", "line", "heatmap"),
scales = c("free_x", "fixed"),
profile_scale = c("measure", "none"),
labels = TRUE,
drop_zero = FALSE,
...
)
## S3 method for class 'net_centrality_group'
plot(
x,
reorder = TRUE,
ncol = 3L,
type = c("bar", "line", "delta"),
scales = c("free_x", "fixed"),
palette = "Set2",
profile_scale = c("measure", "none"),
labels = FALSE,
drop_zero = FALSE,
...
)
Arguments
x |
The network: a |
measures |
The measures to compute. The default is |
loops |
Whether self-loops (staying in a state) count. With |
normalize |
Whether to range-normalise every measure to 0–1, as
|
invert |
Whether a heavier edge is a shorter step in the
shortest-path measures (distance = 1 / weight), as in |
normalize_diffusion |
Whether to range-normalise |
centrality_fn |
A function of your own that takes the weight matrix
and returns a named list of centrality vectors, one per measure; list
their names in |
format |
For a |
... |
Not used. |
n |
For |
digits |
For |
object |
For |
i, j |
For |
reorder |
For the |
ncol |
For the |
type |
For the |
scales |
For the |
profile_scale |
For |
labels |
For the |
drop_zero |
For the |
palette |
For |
Details
Strength is read from the weight matrix directly, and closeness and
betweenness from all-pairs shortest paths (Floyd-Warshall), without
igraph; the values agree with tna::centralities(). Diffusion is
range-normalised by default, which tna does not do.
Range normalisation of a measure that is the same for every node is
undefined and gives NaN, with a warning of class
nestimate_constant_measure. Diffusion on a "relative" network with
loops = TRUE is such a case: each row sums to 1, so every node has the
same diffusion; use normalize_diffusion = FALSE there.
Value
For a netobject or cograph_network: a net_centrality data
frame with one row per node, a state column and one column per
requested measure (the node names are also the row names). For a
netobject_group or an mcml: a net_centrality_group data frame with
one row per network and node, a group column (the network's name), a
state column and one column per measure; with format = "wide", one
row per node. The settings are attributes (measures, groups,
format, ...). print() shows the first n rows rounded, summary()
returns every row as a plain data frame, and plot() draws the
measures per node.
For the plot() methods: a ggplot object.
References
Freeman, L. C. (1978). Centrality in social networks: conceptual clarification. Social Networks, 1(3), 215–239. (betweenness, closeness)
Opsahl, T., Agneessens, F. & Skvoretz, J. (2010). Node centrality in weighted networks: generalizing degree and shortest paths. Social Networks, 32(3), 245–251. (weighted strength and geodesics)
Kivimaki, I., Lebichot, B., Saramaki, J. & Saerens, M. (2016). Two
betweenness centrality measures based on randomized shortest paths.
Scientific Reports, 6, 19668. (BetweennessRSP)
Banerjee, A., Chandrasekhar, A. G., Duflo, E. & Jackson, M. O. (2013). The
diffusion of microfinance. Science, 341(6144), 1236498.
(Diffusion)
Onnela, J.-P., Saramaki, J., Kertesz, J. & Kaski, K. (2005). Intensity and
coherence of motifs in weighted complex networks. Physical Review E,
71, 065103. (Clustering)
Examples
seqs <- data.frame(
V1 = c("A","B","A","C"), V2 = c("B","C","B","A"),
V3 = c("C","A","C","B"))
net <- build_network(seqs, method = "relative")
net_centrality(net)
Undo the pruning of a network
Description
net_deprune() restores the weights a network had before
net_prune(), without recomputing anything, and marks its pruning
inactive. The pruning record stays on the network, so net_reprune()
can re-apply it and net_pruning_details() still lists what the
pruning removed. A netobject_group is restored network by network.
Usage
net_deprune(x, ...)
## S3 method for class 'netobject'
net_deprune(x, ...)
## S3 method for class 'netobject_group'
net_deprune(x, ...)
## Default S3 method:
net_deprune(x, ...)
Arguments
x |
A pruned |
... |
Ignored. |
Value
The input, of the same class, with the original weights, its edge table and edge count updated to them, and its pruning marked inactive.
See Also
Examples
seqs <- data.frame(V1 = c("A","B","C"), V2 = c("B","C","A"),
V3 = c("C","A","B"))
net <- build_network(seqs, method = "relative")
pruned <- net_prune(net, threshold = 0.2)
net_deprune(pruned)
Weight a network's edges by their betweenness
Description
net_edge_betweenness() returns a copy of a network in which each edge's
weight is replaced by its betweenness: the number of shortest paths
between ordered pairs of distinct nodes that pass through that edge, with
a fractional share when several shortest paths tie (Girvan & Newman
2002). It
takes a single network or a netobject_group, which is scored one
network at a time.
With invert = TRUE (the default) a heavier edge is a shorter step, so
the shortest path between two states of a transition network is the most
probable route, not the one with the fewest hops.
Only positive weights count as edges, and a self-loop never lies on a
shortest path, so its betweenness is 0. A directed network gives an
asymmetric betweenness matrix; an undirected one a symmetric matrix,
each cell holding the betweenness of that edge. The result keeps the
source network's directedness (directed when it records none).
An edge with high betweenness carries many of the shortest routes
between states; Girvan & Newman (2002) read such edges as the bridges
between groups of states. To compare the edge betweenness of
two groups, pass two results to permutation() or bayes_compare(),
which resample the source networks behind them; both need two results
with the same source method and invert, and bayes_compare() needs
"relative" source networks.
Usage
net_edge_betweenness(x, invert = TRUE, ...)
## S3 method for class 'netobject'
net_edge_betweenness(x, invert = TRUE, ...)
## S3 method for class 'netobject_group'
net_edge_betweenness(x, invert = TRUE, ...)
## Default S3 method:
net_edge_betweenness(x, invert = TRUE, ...)
## S3 method for class 'net_edge_betweenness'
plot(x, style = c("bar", "forest", "delta"), top_n = NULL, labels = TRUE, ...)
Arguments
x |
A |
invert |
Whether to turn weights into distances by |
... |
Not used. |
style |
For the |
top_n |
For the |
labels |
For the |
Details
Shortest paths come from all-pairs Floyd-Warshall on the distance
matrix (1 / weight, or the weight with invert = FALSE), counting tied
paths with a relative tolerance so that floating-point rounding does not
break a tie. The values agree with tna::betweenness_network() for
transition networks, and on an undirected network each cell equals
igraph::edge_betweenness() for that edge; the function is named
differently to avoid masking either.
Value
For a netobject: a network of class
c("net_edge_betweenness", "netobject", "cograph_network") with method
"edge_betweenness", whose weights are the edge betweenness scores.
It prints like any network; extract_edges() gives one row per edge,
plot() ranks the edges and cograph::splot() draws the network. The
source network's data, metadata, parameters, weights and initial
probabilities are kept on it, which is what lets permutation() and
bayes_compare() test differences in edge betweenness between two
such networks. For a netobject_group: a netobject_group of these
networks, one per group.
For the plot() method: a ggplot object.
Methods
plot() ranks the edges with non-zero betweenness, highest first, one
row per edge (from -> to). It needs no cograph; cograph::splot()
draws the same object as a node-link diagram. A network whose edges all
have zero betweenness raises an error.
References
Girvan, M. & Newman, M. E. J. (2002). Community structure in social and biological networks. Proceedings of the National Academy of Sciences, 99(12), 7821–7826. doi:10.1073/pnas.122653799
Examples
seqs <- data.frame(
V1 = c("A","B","A","C"), V2 = c("B","C","B","A"),
V3 = c("C","A","C","B"))
net <- build_network(seqs, method = "relative")
eb <- net_edge_betweenness(net)
extract_edges(eb)
Prune weak or non-significant edges from a network
Description
net_prune() removes weak or non-significant edges from a network and
returns the pruned network with a record of what it removed, so the
pruning can be undone and re-applied. It is Nestimate's counterpart of
tna::prune(); the net_ prefix avoids a name clash with it. It takes a
netobject or a netobject_group, whose networks are pruned one by one
with the same settings, and offers four methods (see Methods).
Pruning is non-destructive: the network carries a "pruning" attribute
with the original weights, the pruned weights, the settings used and a
table of the removed edges. net_deprune() restores the original weights
and net_reprune() re-applies the pruning, both without recomputing
anything; net_pruning_details() lists what was removed.
"threshold" and "lowest" remove small weights; they do not show that
those edges are absent, and the cut-off is the analyst's choice.
"disparity" and "bootstrap" keep an edge on a statistical criterion.
Before reading a pruned network, see which edges went with
net_pruning_details() and whether the conclusions hold at another
cut-off; bootstrap_network() gives the uncertainty of each edge.
Usage
net_prune(
x,
method = "threshold",
threshold = 0.1,
lowest = 0.05,
level = 0.5,
boot = NULL,
...
)
## S3 method for class 'netobject'
net_prune(
x,
method = "threshold",
threshold = 0.1,
lowest = 0.05,
level = 0.5,
boot = NULL,
...
)
## S3 method for class 'netobject_group'
net_prune(
x,
method = "threshold",
threshold = 0.1,
lowest = 0.05,
level = 0.5,
boot = NULL,
...
)
## Default S3 method:
net_prune(
x,
method = "threshold",
threshold = 0.1,
lowest = 0.05,
level = 0.5,
boot = NULL,
...
)
Arguments
x |
The network: a |
method |
The pruning method: |
threshold |
For |
lowest |
For |
level |
For |
boot |
For |
... |
Arguments for |
Value
The input, of the same class, with the pruned weights, its edge
table and edge count updated to them, and the "pruning" attribute
described above. net_pruning_details() reads the record,
net_deprune() and net_reprune() switch between the original and
the pruned weights. For a netobject_group, each network is pruned
and carries its own record.
Methods
"threshold"Removes positive edges with weight at most
threshold."lowest"Removes positive edges with weight at most the
lowestquantile of the positive weights (self-loops included in the quantile; each pair counted once on an undirected network)."disparity"Keeps the backbone found by the disparity filter of Serrano, Boguna & Vespignani (2009): an edge stays when, at its source's outgoing or its target's incoming edges, its share of the strength is significant at
levelagainst a uniform split of that strength; the filter is defined for non-negative weights."bootstrap"Removes the edges that
bootstrap_network()finds non-significant: pass a computed result asboot, or bootstrap arguments through....
For "threshold" and "lowest", the candidate edges are visited one at
a time, column by column and down each column, and each is removed
only when the network
stays weakly connected without it, so a network that is not weakly
connected to begin with loses no edge to these two methods.
"disparity" and "bootstrap" apply no connectivity check. Negative
edges are never candidates for "threshold" and "lowest", whatever
their size. On a signed network, "disparity" reads the positive edges
only, as the filter is defined for non-negative weights: the strengths
and degrees it divides by are those of the positive edges, and every
negative edge is removed. "bootstrap" removes the non-significant edges
of either sign.
On an undirected network an edge is a pair of cells: it is removed in both directions or kept in both, so the pruned matrix stays symmetric, and the record lists and counts it once.
Self-loops (the diagonal) are observed data: they count towards the
"lowest" quantile but are never removed by any method. This is a
deliberate difference from tna::prune(), which prunes self-loops like
any other edge.
References
Serrano, M. A., Boguna, M., & Vespignani, A. (2009). Extracting the multiscale backbone of complex weighted networks. Proceedings of the National Academy of Sciences, 106(16), 6483–6488. doi:10.1073/pnas.0808904106
See Also
net_deprune, net_reprune,
net_pruning_details
Examples
seqs <- data.frame(
V1 = c("A","B","A","C","B"), V2 = c("B","C","B","A","C"),
V3 = c("C","A","C","B","A"))
net <- build_network(seqs, method = "relative")
pruned <- net_prune(net, method = "threshold", threshold = 0.2)
net_pruning_details(pruned)
List the edges a pruning removed
Description
net_pruning_details() lists the edges that net_prune() removed from a
network, one row per edge, and prints the method with its setting and
the numbers of edges removed and retained above the table. It reads the
pruning record, so it works on a network whose pruning was undone by
net_deprune() as well.
Usage
net_pruning_details(x, ...)
## S3 method for class 'netobject'
net_pruning_details(x, ...)
## S3 method for class 'netobject_group'
net_pruning_details(x, ...)
## Default S3 method:
net_pruning_details(x, ...)
## S3 method for class 'net_pruning_details'
print(x, ...)
Arguments
x |
A pruned |
... |
Ignored. |
Value
For a netobject: a net_pruning_details data frame of the
removed edges, with columns from, to and weight (the weight
before pruning). The method, its setting, the cut-off and the counts
are attributes; print() shows the method, its setting and the
counts. The counts are edges: non-zero cells of either sign
(self-loops included), one per pair on an undirected network. The
retained count is the non-zero edges left after pruning. For a
netobject_group: a named list of such data frames, one per network.
The print() method returns its input invisibly.
See Also
Examples
seqs <- data.frame(
V1 = c("A","B","A","C","B"), V2 = c("B","C","B","A","C"),
V3 = c("C","A","C","B","A"))
net <- build_network(seqs, method = "relative")
net_pruning_details(net_prune(net, threshold = 0.2))
Re-apply the pruning of a network
Description
net_reprune() re-applies a pruning that net_deprune() undid, without
recomputing it: the pruned weights stored by net_prune() come back and
the pruning is marked active again. A netobject_group is handled
network by network.
Usage
net_reprune(x, ...)
## S3 method for class 'netobject'
net_reprune(x, ...)
## S3 method for class 'netobject_group'
net_reprune(x, ...)
## Default S3 method:
net_reprune(x, ...)
Arguments
x |
A depruned |
... |
Ignored. |
Value
The input, of the same class, with the pruned weights, its edge table and edge count updated to them, and its pruning marked active.
See Also
Examples
seqs <- data.frame(V1 = c("A","B","C"), V2 = c("B","C","A"),
V3 = c("C","A","B"))
net <- build_network(seqs, method = "relative")
pruned <- net_prune(net, threshold = 0.2)
undone <- net_deprune(pruned)
net_reprune(undone)
Estimate the split-half reliability of a network
Description
network_reliability() measures how much a network's weights depend on
the particular sample: it splits the sequences (for an association
network, the rows of its data) at random into two halves, estimates the
network on each half with the original network's method and settings,
compares the two weight matrices, and repeats this iter times. Each
comparison gives four numbers: the mean, median and largest absolute
difference between the halves' weights and their Pearson correlation,
taken over all cells of the weight matrix. It takes
one network or several, so the reliability of different methods or
groups can be set side by side; a netobject_group contributes one
network per group.
Each half holds only part of the sequences, so the agreement is that of
networks estimated from a sample of that size. Differences are on the
scale of the weights: counts of a "frequency" network and
probabilities of a "relative" one are not comparable without scale.
To see how far single edges move, use bootstrap_network(); to check
centrality rankings, centrality_stability().
Usage
network_reliability(
...,
iter = 1000L,
split = 0.5,
scale = "none",
seed = NULL
)
## S3 method for class 'net_reliability'
print(x, ...)
## S3 method for class 'net_reliability'
summary(object, ...)
## S3 method for class 'net_reliability'
plot(x, bins = 60L, combined = TRUE, ...)
Arguments
... |
The networks: one or more |
iter |
The number of split-half iterations, at least 2. Default
|
split |
The share of the sequences that goes to the first half, the
rest forming the second, strictly between 0 and 1. Default |
scale |
The rescaling applied to both halves' weight matrices
before they are compared, so that networks on different scales can be
set side by side: |
seed |
A seed for the random splits, so the result repeats exactly.
The session's own random stream is left as it was. Default |
x |
For the |
object |
For the |
bins |
For the |
combined |
For the |
Details
The first half holds round(split * n) of the n sequences (at least
one), the second the rest; a split that leaves the second half empty
(few sequences, split far from 0.5) raises an error of class
nestimate_bad_input. For the transition methods ("relative",
"frequency", "co_occurrence", and one-hot wtna networks, which are
counted the same way), each sequence's transition counts are computed
once and each half is summed from them, as in bootstrap_network().
Other methods are re-estimated on each half of the rows. The network's
own scaling and threshold are applied to both halves. A half on which
the estimator fails, or that loses a variable (a column constant in
that half), gives NA for that iteration, counted in a warning of class
nestimate_resample_failed. The summary leaves out missing values, such
as a correlation that is undefined because one half's weights are all
equal.
Value
A net_reliability object. print() shows the mean and SD of
each metric over the iterations, per network; summary() returns
them as a data frame with one row per network and metric and the
columns model, metric (mean_dev, median_dev, cor,
max_dev), mean and sd; plot() draws their distributions. The
object's fields:
- iterations
A data frame with one row per iteration and network, and the columns
model,mean_dev,median_dev,corandmax_dev.- summary
The table
summary()returns.- models
The networks compared, as a named list.
- iter, split, scale
The settings of the call.
print() returns its input invisibly. plot() draws the histograms
(see Methods) and returns the ggplot invisibly; with
combined = FALSE it returns, without drawing, a list of four
ggplots named by the metric labels ("Max Abs. Diff.",
"Mean Abs. Diff.", "Median Abs. Diff.", "Pearson").
Methods
-
plot(): histograms of the split-half metrics over the iterations, one panel per metric, the mean marked by a dashed line and a label. With several networks, their histograms are overlaid, one colour per network, with a legend below.
See Also
build_network, bootstrap_network
Examples
net <- build_network(data.frame(V1 = c("A","B","C","A"),
V2 = c("B","C","A","B")), method = "relative")
rel <- network_reliability(net, iter = 10)
set.seed(1)
seqs <- data.frame(
V1 = sample(LETTERS[1:4], 30, TRUE), V2 = sample(LETTERS[1:4], 30, TRUE),
V3 = sample(LETTERS[1:4], 30, TRUE), V4 = sample(LETTERS[1:4], 30, TRUE)
)
net <- build_network(seqs, method = "relative")
rel <- network_reliability(net, iter = 20, seed = 42)
print(rel)
Model a unit-level outcome from sequence or network predictors
Description
outcome_model() fits a regression of a unit-level outcome on predictor
columns (pattern indicators, topological features from
simplicial_features(), or any other numeric covariates) and returns a
tidy effect table with confidence intervals and multiplicity-corrected
p-values. A two-valued outcome gets a logistic regression and a numeric
one a linear regression; a group column adds a random intercept per
group, and select = "split" chooses the predictors on one half of the
data and fits them on the other.
Each effect is conditional on the other terms in the model; for a
two-valued outcome, the odds ratio is the factor by which the odds of the
outcome value coded 1 change per unit of the predictor. The p-values are
corrected across every term except the intercept, the adjust covariates
included. A predictor that counts events also measures how long the unit
was observed; enter that exposure through adjust.
Usage
outcome_model(
data,
outcome,
predictors,
group = NULL,
adjust = NULL,
family = c("auto", "binomial", "gaussian"),
select = c("none", "split"),
n_select = 10L,
correction = "BH",
ci_level = 0.95,
seed = NULL
)
## S3 method for class 'net_outcome_model'
print(x, ...)
## S3 method for class 'net_outcome_model'
summary(object, ...)
## S3 method for class 'net_outcome_model'
plot(x, ...)
Arguments
data |
A data frame with one row per unit of analysis. Rows with a
missing value in the outcome, a predictor, an |
outcome |
The outcome column. With |
predictors |
The predictor columns. A predictor that is not numeric
(a logical column included; convert it with |
group |
A grouping column, such as the actor the units are nested
in. When lme4 is installed, a random intercept per group is added,
the right treatment for units nested in actors. lme4 is a
suggested package: without it the random intercept is dropped, a
warning of class |
adjust |
Covariates entered before the predictors. Use it for
exposure: a unit observed longer contains more of every pattern, so an
unadjusted effect can be volume in disguise. Default |
family |
The model family: |
select |
How the predictors are chosen: |
n_select |
The number of predictors kept when |
correction |
The multiplicity correction, any method of p.adjust(). Default
|
ci_level |
The confidence level of the intervals, between 0 and 1.
Default |
seed |
An integer that makes the split reproducible; used only with
|
x |
For the |
... |
For the |
object |
For |
Details
Ordinary gaussian fits use Student t confidence limits with the model's
residual degrees of freedom; binomial and mixed fits use normal (Wald)
limits. A linear mixed model (lme4::lmer()) reports no p-values,
so they are computed from the normal distribution of its t statistics.
Value
A net_outcome_model object. print() shows the outcome and
family, the number of units (and groups), the number of selected terms,
the adjustments, the dropped predictors and the correction, followed by
the effect table, and returns its input invisibly. summary() and
effects_table() return the effect table without the intercept,
rounded to three decimals except the p-values; effects_table() also
keeps the intercept, or only the significant terms, on request.
plot() returns a ggplot forest plot of the effects (odds ratios for
a binomial fit, against a dashed line at no effect), with filled markers
for terms whose corrected p-value is below 0.05. The object's fields:
- effects
The effect table: a data frame with one row per model term, the intercept and the
adjustcovariates included, and columnsterm,estimate,std_error,statistic,ci_lower,ci_upper,p_valueandp_adj(NAon the intercept row, which is left out of the correction), plusodds_ratio,or_lowerandor_upperfor a binomial fit.- model
The fitted model: a
glm, or an lme4 fit when a random intercept was added.- family
"binomial"or"gaussian".- n
The number of rows the reported model was fitted on.
- n_groups
The number of groups;
NAunless a random intercept was fitted.- selected
The predictors in the reported model.
- dropped
The predictors dropped as non-numeric or constant.
- adjust, select, correction, ci_level, outcome
The settings used.
- mixed
Whether a random intercept was fitted.
Honest inference
Choosing predictors by their association with the outcome and then
testing them on the same rows invalidates the p-values. With
select = "split" the data is halved: predictors are ranked on one half
and the reported model is fitted on the other, so the returned inference
is valid for the selected set. With a group, the groups are halved, so
no group has rows in both halves. select = "none" (default) fits every
supplied predictor and needs no split.
See Also
simplicial_features, effects_table
Examples
set.seed(1)
d <- data.frame(
hint = rbinom(300, 1, 0.4),
think = rbinom(300, 1, 0.3),
n_events = rpois(300, 20),
actor = rep(letters[1:10], each = 30)
)
d$success <- rbinom(300, 1, plogis(-0.5 + 0.8 * d$hint))
fit <- outcome_model(d, outcome = "success",
predictors = c("hint", "think"),
adjust = "n_events")
effects_table(fit)
Compute the mean first passage times of a Markov chain
Description
passage_time() computes the mean first passage times of a Markov chain:
the entry in row i and column j is the expected number of
steps a chain started in state i takes to reach state j for
the first time, and the diagonal entry is the mean recurrence time,
the expected number of steps to return to state i. On an
irreducible chain it equals 1/\pi_i.
The stationary distribution \pi is returned with them. It reads a
transition network, a tna model, a transition matrix or wide sequences,
and analyses a grouped network one network at a time.
The times describe the estimated chain, in which a transition never seen
in the data counts as impossible. In an irreducible chain every state can
be reached from every other and every time is finite; in any other chain
a time into a state that is not reached with certainty is Inf (see
Details), so check the structure with chain_structure() first. markov_stability() condenses the matrix into
per-state summaries beside each state's persistence and sojourn time.
Usage
passage_time(x, states = NULL, normalize = TRUE)
## S3 method for class 'net_mpt'
print(x, digits = 1, ...)
## S3 method for class 'net_mpt_group'
print(x, ...)
## S3 method for class 'net_mpt'
summary(object, table = c("states", "pairs"), ...)
## S3 method for class 'net_mpt_group'
summary(object, table = c("states", "pairs"), ...)
## S3 method for class 'net_mpt'
plot(
x,
log_scale = TRUE,
digits = 1,
title = "Mean First Passage Times",
low = "#004d00",
high = "#ccffcc",
...
)
## S3 method for class 'net_mpt_group'
plot(
x,
log_scale = TRUE,
digits = 1,
title = "Mean First Passage Times",
low = "#004d00",
high = "#ccffcc",
...
)
Arguments
x |
The chain: a |
states |
The states to keep in the result. The times are computed
on the whole chain and then subset, so they still count paths through
the states left out. A name that is not a state raises an error.
Default |
normalize |
Whether to rescale rows that do not sum to 1 so that
they do, with a warning, as for a |
digits |
Decimal places of the printed matrix ( |
... |
For |
object |
For the |
table |
For |
log_scale |
For the |
title |
For the |
low, high |
For the |
Details
The times follow the Kemeny-Snell fundamental matrix formula:
M_{ij} = \frac{Z_{jj} - Z_{ij}}{\pi_j}, \quad
Z = (I - P + \Pi)^{-1}
where \Pi_{ij} = \pi_j, and \pi is the left eigenvector
of P for eigenvalue 1, scaled to sum to 1. The fundamental matrix
exists for every irreducible chain (an ergodic chain in Kemeny and
Snell's terms), periodic ones included.
A chain that is not irreducible (for example one with an absorbing state,
or with several closed classes) has no fundamental matrix. Its times are
the expected hitting times: the time from i to j is Inf
when the chain started in i may never reach j, and
otherwise the minimal non-negative solution of
m_i = 1 + \sum_{k \ne j} P_{ik} m_k (Norris, 1997). Times into
the states outside a closed class are therefore Inf from inside it, and
times into the closed class are finite from every state that cannot
avoid it. The diagonal is the mean return time, Inf for a transient
state. On an irreducible chain both routes give the same matrix.
Nestimate 1.0.9 and earlier raised the zero stationary probabilities to
machine precision instead, giving times near 10^{15} with a
warning, and stopped with an error for a chain with several closed
classes.
Value
A net_mpt object; for a netobject_group, a net_mpt_group,
a named list holding one net_mpt per group. print() shows the
passage-time matrix and the stationary distribution. summary()
returns a data frame with one row per state: state, return_time (mean recurrence time),
stationary (\pi_i), mean_out (the mean number of steps from
the state to the others) and
mean_in (the mean number of steps from the others to the state),
rounded to 2 decimals (stationary to 4); with table = "pairs", one
row per ordered pair of states, the diagonal included (from, to,
passage_time). plot() returns a ggplot
heatmap of the matrix, rows the starting state and columns the target;
for a net_mpt_group, one panel per group on a shared colour scale.
The print() methods return their input invisibly. A net_mpt holds:
- matrix
The
n \times nmatrix of mean first passage times: rowi, columnjis the expected number of steps from stateito statej; the diagonal is the mean recurrence time, equal to1/\pi_ion an irreducible chain.- stationary
The stationary distribution
\pi, a named numeric vector; zero outside the closed class of a chain with one closed class, andNAfor a chain with several, whose stationary distribution is not unique.- return_times
The mean recurrence time of each state (the diagonal of
matrix), a named numeric vector:1/\pi_iin an irreducible chain,Inffor a transient state.- states
The state names.
For summary() of a net_mpt_group: a data frame with one row
per group and state (or pair, with table = "pairs"), the group
column followed by the columns of the single-network table.
References
Kemeny, J.G. and Snell, J.L. (1976). Finite Markov Chains. Springer-Verlag.
Norris, J. R. (1997). Markov Chains. Cambridge University Press.
See Also
markov_stability, build_network
Examples
net <- build_network(as.data.frame(trajectories), method = "relative")
pt <- passage_time(net)
print(pt)
plot(pt)
Count the paths of k states in trajectories
Description
path_counts() counts how often each path of k consecutive states
(a k-gram) occurs across all trajectories, and returns one row per path,
most frequent first. Every position of a trajectory starts a path, so the
paths of one trajectory overlap. The counts are descriptive: they show
which runs of states dominate the data before a model such as
build_mogen() or build_hon() is fitted to them.
Usage
path_counts(data, k = 2L, top = NULL)
Arguments
data |
The trajectories: a list of state vectors, a data frame or
character matrix with one row per trajectory and one column per time
point, a |
k |
The number of states in each path, a whole number of at least
2; a non-integer value is an error, not truncated. Default |
top |
The number of most frequent paths to keep. Default |
Value
A data frame with one row per distinct path, sorted by count
(descending), with columns path (the k states in arrow notation, such
as "A -> B"), count and proportion (the path's share of all paths
counted, rounded to 4 decimal places). When no trajectory holds k
consecutive observed states, the data frame has no rows.
Examples
trajs <- list(c("A","B","C","D"), c("A","B","D","C"))
path_counts(trajs, k = 2)
path_counts(trajs, k = 3, top = 10)
Measure the path dependence of each context at order k
Description
path_dependence() shows, context by context, where a first-order
Markov chain misses what longer histories say about the next state. For
every context of k = order consecutive states
c = (s_1, \ldots, s_k), it compares the
observed distribution of the next state after that context,
P_k(s_{k+1} \mid c), with the first-order
prediction P_1(s_{k+1} \mid s_k) from the last
state alone. Its table has one row per context, sorted by the
Kullback-Leibler divergence between the two, with both entropies and
whether the most likely next state changes. It reads wide sequence data
or a network built from sequences.
A KL of 0 means the longer history adds nothing in that context; a
positive entropy drop means it sharpens the prediction; and a flip means
it changes which next state is most likely, not only how confident the
prediction is. The values are computed from the observed counts and
come without a test, and a context seen a few times gives a noisy KL:
read n beside it and raise min_count when small contexts lead the
table. Whether order k is needed for the chain as a whole is tested by
markov_order_test(); path_dependence() breaks that decision down by
context.
Usage
path_dependence(x, order = 2L, min_count = 5L, base = 2)
## S3 method for class 'net_path_dependence'
print(x, top = 10L, digits = 3L, ...)
## S3 method for class 'net_path_dependence'
summary(object, ...)
## S3 method for class 'summary.net_path_dependence'
print(x, digits = 3L, ...)
## S3 method for class 'net_path_dependence'
plot(x, top = 15L, title = NULL, ...)
Arguments
x |
The sequences: a wide data frame or matrix (one row per sequence,
one column per time step), or a |
order |
The length k of the conditioning context, a whole number of
at least 2; a non-integer value is an error, not truncated. Default
|
min_count |
The number of times a context must be observed to be
reported, a whole number of at least 1. Default |
base |
The logarithm base for the entropies and the KL divergence:
|
top |
For the |
digits |
For the |
... |
For the |
object |
For the |
title |
For the |
Details
For each context c observed at least min_count times, the
function computes:
the empirical conditional
P_k(\cdot \mid c)from the counts of the paths of k + 1 states;the first-order prediction
P_1(\cdot \mid s_k)from the most recent state alone, estimated from all pairs of consecutive states;the entropy drop
H(P_1) - H(P_k), the uncertainty removed by the longer memory in this context;the Kullback-Leibler divergence
D_{KL}(P_k \,\|\, P_1), the expected extra surprise of predicting with the first-order model when the order-k distribution holds.
A negative H_drop means the order-k context spreads its probability
over more outcomes than the last state alone does, which can be
small-sample noise or uncertainty the context adds; inspect n.
Value
A net_path_dependence object. print() shows the chain-level
summaries and the top contexts by KL; summary() returns a
summary.net_path_dependence holding the full sorted table, which
prints every context and the chain-level summaries; plot() returns a
ggplot lollipop chart of each context's KL, highest first, with point
size proportional to the context's count and the contexts whose modal
next state flips coloured and labelled with the change. The print()
methods return their input invisibly. The object's fields:
- contexts
Data frame with one row per context, sorted by KL (descending), with columns
context(such as"A -> B"),n(its count),H_order1(entropy ofP_1(\cdot \mid s_k)),H_orderk(entropy ofP_k(\cdot \mid c)),H_drop(H_order1 - H_orderk),KL(D_{KL}(P_k \| P_1)),top_o1(the most likely next state under order 1),top_ok(the most likely next state under order k) andflips(whether the two differ).- chain
List of chain-level summaries:
KL_weighted(the count-weighted mean KL over contexts),H_drop_weighted(the count-weighted mean entropy drop),n_contextsandn_flips(the number of contexts whose most likely next state changes).- order
The context length used.
- base
The logarithm base used.
- min_count
The minimum context count used.
- states
The states observed.
References
Cover, T.M. & Thomas, J.A. (2006). Elements of Information Theory, 2nd ed., chapters 2 and 4. Wiley. (KL divergence and conditional entropy.)
See Also
markov_order_test, transition_entropy,
build_mogen
Examples
data(trajectories, package = "Nestimate")
pd <- path_dependence(as.data.frame(trajectories), order = 2)
print(pd)
summary(pd)
plot(pd)
Extract pathways from a higher-order network
Description
pathways() turns a higher-order result into pathway strings in arrow
notation, "A B -> C": the states before the arrow lead, together, to the
state after it. The strings are what cograph::plot_simplicial() draws,
one simplex per pathway. Which pathways are returned depends on the input:
a
net_hongives its higher-order edges, those whose source node has order above 1, i.e. the transitions that differ from a first-order Markov chain, ranked by count;a
net_hypagives its anomalous paths, over- or under-represented relative to the hypergeometric null model, the over-represented ones first;a
net_mogengives every transition at the optimal order (or the order given), ranked by count;a
netobjectbuilt from sequences is first turned into a HON or a HYPA, and that result's pathways are returned;a
net_association_rulesgives its rules{A, B} => {C}as"A B -> C": antecedent items become the sources, consequent items the target. Rules whose antecedent and consequent together hold the same items describe the same simplex, so only the highest-lift rule per item set is kept; the rules are ranked by lift, then confidence;a
net_link_predictiongives its predicted links, ranked by score; withevidence = TRUEeach predicted edgeA -> Bis extended with the common neighbours that support it,"A cn1 cn2 -> B".
The strings keep only which pathways passed the filters, not the counts,
probabilities, scores or tests behind them; those stay in the source
object (for a MOGen, mogen_transitions() gives them per order).
Usage
pathways(x, ...)
## S3 method for class 'net_hon'
pathways(x, min_count = 1L, min_prob = 0, top = NULL, order = NULL, ...)
## S3 method for class 'net_hypa'
pathways(x, type = "all", ...)
## S3 method for class 'netobject'
pathways(x, ho_method = c("hon", "hypa"), ...)
## S3 method for class 'net_association_rules'
pathways(x, top = NULL, min_lift = NULL, min_confidence = NULL, ...)
## S3 method for class 'net_link_prediction'
pathways(x, method = NULL, top = 10L, evidence = TRUE, max_evidence = 3L, ...)
## S3 method for class 'net_mogen'
pathways(x, order = NULL, min_count = 1L, min_prob = 0, top = NULL, ...)
Arguments
x |
The object to read:
A |
... |
For the |
min_count |
For a HON or a MOGen: the smallest transition count
kept, which filters out rare observations. Default |
min_prob |
For a HON or a MOGen: the smallest transition probability
kept. Default |
top |
How many pathways to keep after ranking: by count for a HON or
a MOGen, by lift then confidence for association rules (after the item
sets are de-duplicated), and by score for link predictions. Default
|
order |
For a HON: keep only pathways whose source has this order.
Default |
type |
For a HYPA: which anomalies to include, |
ho_method |
For a |
min_lift |
For association rules: the smallest lift kept, on top of
the threshold the rules were mined with. Default |
min_confidence |
For association rules: the smallest confidence
kept, on top of the mining threshold. Default |
method |
For link predictions: the prediction method whose links are
returned. Default |
evidence |
For link predictions: whether to extend each predicted
link |
max_evidence |
For link predictions with |
Value
A character vector of pathway strings in arrow notation (e.g.
"A B -> C"), one per pathway and in the ranking order described above,
ready for cograph::plot_simplicial(). Every method returns this shape,
and character(0) when nothing passes its filters.
Methods (by class)
-
pathways(net_hon): Higher-order edges of a HON. -
pathways(net_hypa): Anomalous paths of a HYPA. -
pathways(netobject): Higher-order pathways of a network's sequences. -
pathways(net_association_rules): Association rules as pathways. -
pathways(net_link_prediction): Predicted links as pathways. -
pathways(net_mogen): Transitions of a MOGen at one order.
Examples
seqs <- list(c("A","B","C","D"), c("A","B","C","A"))
hon <- build_hon(seqs, max_order = 3)
pw <- pathways(hon)
trans <- list(c("A","B","C"), c("A","B"), c("B","C","D"), c("A","C","D"))
rules <- association_rules(trans, min_support = 0.3, min_confidence = 0.3,
min_lift = 0)
pathways(rules)
seqs <- data.frame(
V1 = sample(LETTERS[1:5], 50, TRUE),
V2 = sample(LETTERS[1:5], 50, TRUE),
V3 = sample(LETTERS[1:5], 50, TRUE)
)
net <- build_network(seqs, method = "relative")
pred <- predict_links(net, methods = "common_neighbors")
pathways(pred)
Model a binary outcome from sequential patterns
Description
pattern_outcome() selects the n sequential patterns most associated
with a two-valued outcome and fits one logistic regression of the
outcome on their presence (or their counts), returning one row per
selected pattern with its log odds ratio, odds ratio and Wald interval.
It reads any sequence data extract_sequences() reads, takes the
outcome from a stored covariate, a vector or each sequence's last state,
and can adjust for covariates and add a random intercept per actor.
Each estimate is the association of one pattern with the outcome,
adjusted for the other selected patterns and the covariates; it is not a
causal effect. The patterns are chosen by their association with the
outcome in the same data the model is fitted to, so the p-values do not
account for that selection and overstate the evidence: treat them as a
ranking, or confirm the selected patterns on new data. A pattern and a
longer pattern containing it often occur together, and each coefficient
is then adjusted for the other; sequence_patterns() shows how often
each pattern occurs, overall and by group.
Usage
pattern_outcome(
x,
outcome = "last_obs",
type = c("ngram", "gapped", "repeated"),
len = 1:2,
gap = 1,
min_freq = 5,
min_support = 0.01,
start = NULL,
end = NULL,
contain = NULL,
n = 10,
priority = "chisq",
desc = TRUE,
occurrences = FALSE,
adjust = NULL,
adjust_length = FALSE,
group = NULL,
reference = NULL,
ci_level = 0.95,
cols = NULL,
actor = NULL,
action = NULL,
time = NULL,
...
)
Arguments
x |
The sequence data, in any form |
outcome |
The outcome, with exactly two distinct values: the name of
a column stored with the sequences (a covariate of a wide data frame or
long event log, or of a network's metadata), or a vector with one value
per sequence; use a vector for a model that stores no covariates, such
as a |
type, len, gap, min_freq, min_support, start, end, contain |
The pattern
definition and filters; see |
n |
The number of patterns entered into the model, a positive whole
number. Default |
priority |
The columns ranking the patterns for selection, applied
in order: |
desc |
Whether each |
occurrences |
Whether each pattern enters the model as its number of
occurrences in the sequence instead of its presence (0/1). Default
|
adjust |
Covariate columns added to the model. Default |
adjust_length |
Whether to add the number of observed states per
sequence as a covariate. Default |
group |
The column identifying the actor (or other cluster) each
sequence belongs to; it adds a random intercept per group. It needs
lme4, otherwise an error of class |
reference |
The reference outcome value; the odds ratios are for
the other value. Default |
ci_level |
The confidence level of the Wald intervals, a number
between 0 and 1. Default |
cols |
The state columns of a wide data frame; see
|
actor, action, time |
The actor, action and timestamp columns of a
long event log; setting |
... |
Further arguments passed to |
Details
pattern_outcome() reproduces codyna::analyze_outcome(): the same
pattern discovery and filters, the same ranking and the same model, so
the coefficients agree. The steps:
Patterns are found as in
sequence_patterns()and filtered bymin_freq,min_support,start,endandcontain. Patterns absent from all sequences of one outcome value are dropped.Each pattern gets the chi-square statistic of the number of sequences containing it under each outcome value, against an equal split across the values (codyna's statistic; it does not weight by the size of each outcome group).
The top
npatterns bypriorityenter one model,outcome ~ adjust + pattern_1 + ... + pattern_n, as presence indicators (or occurrence counts withoccurrences = TRUE). Ties keep codyna's order: more occurrences first, then first appearance. Withgroup, a random intercept per group is added (lme4::glmer()); otherwise the model is a plainglm().
Value
A data frame with one row per selected pattern, ordered by
pattern name, with the columns pattern, length, occurrences,
n_sequences, support and lift (as in sequence_patterns()); the
share of the sequences of each outcome value that contain the pattern
(support_<value>); chisq (the selection statistic); estimate (the
log odds ratio, adjusted for the other terms), std_error, ci_lower,
ci_upper and p_value (Wald z); and odds_ratio, or_lower and
or_upper.
Raises the warning nestimate_missing_outcome when it drops sequences with a missing outcome, covariate or group. A selected pattern collinear with the other terms keeps its descriptive columns but gets NA estimates, intervals, p-value and odds ratios, with a warning. Warnings from the model fit (such as
separation) are passed on unchanged.
References
Saqr, M., Tikka, S., & López-Pernas, S. (2026). codyna: Complex Dynamic Systems. R package version 1.0.0.
See Also
Examples
pattern_outcome(group_regulation_long, outcome = "Achiever",
actor = "Actor", action = "Action", time = "Time")
Test whether two networks differ by permutation
Description
permutation() tests whether two networks differ more than chance would
produce. The sequences (or, for association networks, the rows) behind
both networks are pooled, the group labels are shuffled iter times, both
networks are re-estimated on every shuffle, and each observed difference
is compared with the shuffled ones. It tests every edge, the network as a
whole and, with measures, the nodes' centralities.
It compares two netobjects from build_network() estimated with the
same method on the same nodes, for every built-in method and for
registered estimators whose result keeps the data (cleaned_data, see
register_estimator()). A netobject_group (or an mcml, converted with
as_tna()) is tested pair by pair: every pair of its groups when y is
NULL, or the groups of the same name in a second netobject_group. Two
wtna_mixed results of wtna() are tested on their transition and
co-occurrence networks, and two net_edge_betweenness() results on their
edge betweenness.
A small p-value says that the observed difference is larger than the
shuffles produce; it does not say how large or how probable the
difference is, which bayes_compare() estimates. With many edges, some
fall below alpha by chance: set adjust to correct for that. The
shuffle treats every sequence as exchangeable; when sequences are nested
in persons or teams, set actor, and see what the nesting changes with
permutation_diagnostics().
Usage
permutation(
x,
y = NULL,
iter = 1000L,
alpha = 0.05,
paired = FALSE,
adjust = "none",
measures = NULL,
nlambda = NULL,
seed = NULL,
actor = NULL
)
## S3 method for class 'net_permutation'
print(x, ...)
## S3 method for class 'net_permutation'
summary(object, ...)
## S3 method for class 'net_permutation_group'
print(x, ...)
## S3 method for class 'net_permutation_group'
summary(object, ...)
## S3 method for class 'wtna_perm_mixed'
print(x, ...)
## S3 method for class 'wtna_perm_mixed'
summary(object, ...)
Arguments
x |
The first network:
For the |
y |
The second network, of the same kind as |
iter |
The number of shuffles, at least 2. Default |
alpha |
The significance level, strictly between 0 and 1, that marks
an edge or centrality as significant ( |
paired |
Whether the two networks hold paired observations (the
i-th sequence or row of |
adjust |
The multiplicity correction for the p-values, a method of
|
measures |
Centrality measures to test as well as the edges: any of
|
nlambda |
Ignored, kept so existing calls run. Default |
seed |
An integer that makes the shuffles reproducible. Default
|
actor |
The column identifying the actor each sequence belongs to:
the person whose sessions they are, or the team of a student. It is
looked up in the network's metadata (such as |
... |
For the |
object |
For the |
Details
For transition methods, per-sequence count matrices are computed once and
each shuffle only re-sums them, which keeps a large iter fast; the
networks' scaling and threshold are applied to every shuffled network
as to the observed one. For the other methods the estimator is re-run on
every shuffle (cor and pcor through a lighter direct path).
A network built with method = "latency" (alone or in a group) raises an
error of class nestimate_latency_resampling; bootstrap_network() is the
verb that resamples latency networks.
For glasso, every shuffled network is estimated as build_network()
estimated the observed ones, with x's params (each sample's own
lambda path, nlambda, lambda.min.ratio, gamma,
penalize.diagonal, refit), so the observed difference and its null
come from one estimator (van Borkulo et al. 2022). Two glasso networks
built with different settings raise an error of class
nestimate_bad_input.
A network that rests on one sequence, or one-hot data with no actor or
session, has nothing to shuffle and raises an error of class
nestimate_single_sequence. A sequence network with no observed
transition raises an error of class nestimate_no_transition.
Wide rows combined with params = list(concat = k) are shuffled as the
merged sequences the estimator used, keeping their internal joins. A
merged sequence must lie within one actor when actor is set (class
nestimate_actor_misaligned otherwise), and paired tests need the same
number of merged sequences. Both networks must use the same weighted
setting (class nestimate_bad_input otherwise).
A refit that fails or produces non-finite weights makes the permutation
statistic undefined for that shuffle. The test then raises an error of
class nestimate_permutation_failed that reports the number of failed
shuffles, and returns no p-values: failed shuffles are neither counted as
non-exceedances nor dropped from the null.
For net_edge_betweenness() input, the source networks are shuffled and
edge betweenness is recomputed on each shuffle. Both objects must come
from the same source method and use the same invert setting.
The centrality block follows the layout of
tna::permutation_test(measures = ): a centrality whose shuffled
differences do not vary gets an effect size of NaN or Inf, as there,
rather than the 0 the edge table uses.
Value
A net_permutation object. print() shows the settings, the
number of edges tested and significant, the global test and, with
actor, the ICC and design effects; summary() returns the edge table,
one row per edge present in either network; cograph::splot() draws
the difference network. Grouped input gives a net_permutation_group, a
named list of net_permutation results (one per group pair, named
"<group i> vs <group j>", when y is NULL; one per shared group
name otherwise), whose print() prints each and whose summary()
stacks the edge tables with a leading group column naming the pair or
group. Two wtna_mixed inputs give a wtna_perm_mixed, the
net_permutation results of the transition and cooccurrence
networks, whose print() prints both and whose summary() returns a
list of their two edge tables. The print() methods return their input
invisibly. The net_permutation's fields:
- x, y
The two networks compared.
- diff
The observed difference matrix,
x - y.- diff_sig
The observed difference where
p < alpha, else 0.- p_values
The p-value matrix (adjusted when
adjustis not"none").- effect_size
The effect-size matrix: the observed difference divided by the SD of the shuffled differences.
- summary
The edge table
summary()returns: one row per edge present in either network (an undirected network has one row per unordered pair), with columnsfrom,to,weight_x,weight_y,diff,effect_size,p_valueandsig.- global
The global test, one row per statistic:
statistic("M", the sum of absolute differences, and"S", the largest absolute difference),observed, andp_valuefrom the same shuffles as the edge test. Absent for edge-betweenness input.- method
The network estimation method (
"edge_betweenness"for edge-betweenness input).- source_method
For edge-betweenness input: the source networks' method.
- edge_betweenness
For edge-betweenness input: the
invertsetting and the source method used.- iter, alpha, paired, adjust
The settings used.
- actor
The
actorcolumn name (or names, outermost first), orNULL.- n_actors
The number of distinct actors (with several levels, at the innermost level), or
NULL.- actor_levels
Only with several
actorlevels: one row per level, withlevel(the column),n_actors(the units at that level),n_pureandn_crossed(the units the shuffle met at that level, inside crossed units of the level above, that sit in one group or in both) anddesign("between","within","mixed", or"not opened"when no unit above was crossed).- null_sd
The SD of each edge's shuffled differences (the effect-size denominator), as a matrix.
- null_sd_m
The SD of the global statistic M over the shuffles. Absent for edge-betweenness input.
- clustering
Only with
actor: a one-row data frame withn_sequences,n_actors,design("between","within"or"mixed"; with several levels, one"<level>: <design> (<n> actors)"entry per level),icc(at the innermost level) withicc_ci_lowerandicc_ci_upper(how alike the sequences of one actor are),deff_edges(the median design effect over edges),deff_global(the design effect for M) andmin_p, the smallest p-value the exact test over the actors' arrangements can give: one over their number, or1 / (iter + 1)when larger. The reported p-values are Monte Carlo estimates, so with few arrangements one can fall below it by chance.- clustering_edges
Only with
actor: one row per edge of the edge table, withfrom,to,icc,null_sd_actor,null_sd_sequenceanddeff.- centralities
Only with
measures: a list ofstats(one row per state and measure, withstate,centrality,diff_true,effect_sizeandp_value),diffs_true(the observed differences, one row per state and one column per measure) anddiffs_sig(the same wherep < alpha, else 0).
What is tested
Two kinds of question are answered from the same shuffles.
- Edge tests
One test per edge: is the difference in this edge's weight,
x - y, larger in absolute value than the shuffles produce?summary()reports each with an effect size (the observed difference divided by the SD of the shuffled differences, 0 when that SD is 0) and a p-value,(number of shuffles at least as extreme + 1) / (iter + 1).- Global test
One test for the whole network: do the two networks differ at all? Two statistics: M, the sum of the absolute differences over all cells of the weight matrix (the total amount of difference; an undirected edge counts twice), and S, the largest absolute difference. Being a single test, it needs no multiplicity correction.
print()shows it.
The letters follow this function's historical convention. In nct(), M
is instead the largest absolute edge difference and S the difference in
global strength; the sum of absolute edge differences here measures total
edge difference, not a difference in global strength. The smallest
attainable p-value is 1 / (iter + 1); with the default iter = 1000 it
is 0.000999, meaning that no shuffle came close.
Nested data and actor
Shuffling treats every sequence as an exchangeable unit. When several
sequences come from the same actor (sessions of one person, students of
one team), actor names the column identifying that actor, and the
shuffle respects it (Good, 2005; Anderson & ter Braak, 2003): an actor
whose sequences are all in one group moves to the other group as a whole,
and an actor with sequences in both groups has their labels shuffled
among their own sequences only. Mixed designs combine the two. The
observed differences do not change; only the p-values and effect sizes
do. With few actors there are few distinct ways to shuffle them, and a
warning of class nestimate_few_actors is raised when no p-value could
fall below alpha.
Several columns, outermost first (actor = c("Group", "Student"), students
within teams), name nested levels; the unit at each level is the
combination of its column with the ones before it. A level that adds no
units below the one before it (the levels given innermost first) raises
an error of class nestimate_bad_actor. A column whose ids repeat across
the units of the next column (a class code reused in every team) cannot
be told apart from a correctly nested one, so the order of the columns is
the caller's statement of the design. The labels are then
shuffled at the level where they are assigned, within the units above it
(Anderson & ter Braak, 2003; Good, 2005): teams whose sequences are all in
one group move as wholes among such teams, exactly as with one column; a
team with sequences in both groups is opened, and inside it the students
all in one group exchange labels with each other (never with students of
another team), while a student in both groups is opened in turn, down to
the last column, inside which single sequences exchange labels. Set the
levels whenever the groups are assigned below the top level (students of
one team in different conditions): actor = "Group" alone would then
shuffle single sequences within each team and treat the sessions of one
student as independent. The number of distinct arrangements, the
nestimate_few_actors check and min_p follow the whole scheme. One
column, or NULL, runs exactly the scheme described above.
When to set actor: when the groups are made of different actors (high-
versus low-achieving students, each student in one group), set it.
Shuffling single sequences then treats the sequences of one actor as
independent, and the test is too liberal. In one data set of sessions
nested in students, two groups of different students with no true
difference had 11.7% of edges significant at alpha = 0.05 when
sessions were shuffled (23% of replicates had at least one significant
edge after Benjamini-Hochberg correction), against 4.6% (0.5%) when
whole students were shuffled. When the groups vary within the same
actors (pre- and post-test sessions of the same students), actor
shuffles the labels within each actor; the plain test gave similar size
in that simulation (5.1% against 5.0%). This does not establish validity
for other within-actor designs: the permitted shuffles must respect the
assignment mechanism or exchangeability under the null. Whether nesting
matters is decided by the design effect, not by the ICC alone: in that
data set the transitions of one student correlated at about 0.01, yet
with about 59 transitions per student (size-weighted mean) the Rao-Scott
design effect of the transition table was about 1.5 (mosaic_test()).
The printed ICC is a different quantity, the correlation between the
sequences of one actor (0.05 in that data set, with a printed design
effect of 1.24 for the bootstrap), so Kish's approximation with it
counts sequences per actor, not transitions.
actor works for the transition networks built from sequences: "relative", "frequency" and "co_occurrence". The other methods keep no row identifiers after estimation, and with them actor raises nestimate_actor_unsupported; one-hot data, which hold the actor per row, raise nestimate_actor_misaligned.
ICC and design effect
With actor, print() also reports:
- ICC
The intraclass correlation, the proportion of the total variance that lies between actors (Shrout & Fleiss, 1979). An ICC close to 0 indicates little evidence of a nesting effect. It is the one-way ANOVA ICC of each sequence's transition shares within each group, averaged over edges weighted by edge frequency and jackknife bias-corrected, with a 95% interval from the leave-one-actor-out jackknife (Efron & Tibshirani, 1993). With several
actorlevels it is computed at the innermost level (the finest actor, such as the student within a team), andprint()says so.- Design effect
The ratio of the variance of an estimate under the clustered design to its variance had the units been sampled independently (Kish, 1965). Here it is the variance of the shuffled differences when whole actors are moved, divided by the variance when single sequences are moved (with several levels: under the whole nested scheme), both drawn in the same run, reported as the median over edges and for the global statistic M. For equal numbers of sequences per actor m, Kish gives the approximation
1 + (m - 1) * ICC.
Reading the printed output
Permutation Test: Transition Network (relative probabilities) [directed] Iterations: 1000 | Alpha: 0.05 | Actor: Group (200 actors) Nodes: 9 | Edges tested: 78 | Significant: 42 Global test (networks differ overall?): M = 2.612 (p = 0.000999) | ... Nesting in Group: ICC = -0.002 [95% CI -0.006, 0.002] | between design Design effect (1 = nesting does not matter): edges 1.03 | global 1.20
Line 2: the settings, and the actor column with its number of actors.
Line 3: the edges present in either network and how many differ at
alpha. Line 4: the global test. Lines 5 and 6, only with actor: the
ICC with its interval, whether actors sit in one group (between), in
both (within) or either (mixed), and the design effects. With actor,
when min_p is above alpha (too few actors for the exact test, or too
small an iter), a last line says so. With several actor levels, line 2
names the levels (Actor: Group > Student (nested)), and line 5 is
replaced by two: the design at every level, with its number of actors
(Design: Group: mixed (200 actors), Student: between (2000 actors)), and
the ICC at the innermost level.
References
Anderson, M. J., & ter Braak, C. J. F. (2003). Permutation tests for multi-factorial analysis of variance. Journal of Statistical Computation and Simulation, 73(2), 85-113.
Efron, B., & Tibshirani, R. J. (1993). An Introduction to the Bootstrap. Chapman & Hall.
Good, P. (2005). Permutation, Parametric, and Bootstrap Tests of Hypotheses (3rd ed.). Springer.
Kish, L. (1965). Survey Sampling. Wiley.
Shrout, P. E., & Fleiss, J. L. (1979). Intraclass correlations: Uses in assessing rater reliability. Psychological Bulletin, 86(2), 420-428.
van Borkulo, C. D., van Bork, R., Boschloo, L., Kossakowski, J. J., Tio, P., Schoevers, R. A., Borsboom, D., & Waldorp, L. J. (2023). Comparing network structures on three aspects: A permutation test. Psychological Methods, 28(6), 1273-1285.
See Also
permutation_diagnostics() to compare the actor-level and
ordinary tests side by side; bayes_compare() for the Bayesian
complement, which instead of "is this difference more extreme than
chance?" answers "how probable is a difference, and how large?";
build_network(), bootstrap_network()
Examples
s1 <- data.frame(V1 = c("A","B","C"), V2 = c("B","C","A"))
s2 <- data.frame(V1 = c("A","C","B"), V2 = c("C","B","A"))
n1 <- build_network(s1, method = "relative")
n2 <- build_network(s2, method = "relative")
perm <- permutation(n1, n2, iter = 10)
set.seed(1)
d1 <- data.frame(V1 = sample(LETTERS[1:4], 20, TRUE),
V2 = sample(LETTERS[1:4], 20, TRUE),
V3 = sample(LETTERS[1:4], 20, TRUE))
d2 <- data.frame(V1 = sample(LETTERS[1:4], 20, TRUE),
V2 = sample(LETTERS[1:4], 20, TRUE),
V3 = sample(LETTERS[1:4], 20, TRUE))
net1 <- build_network(d1, method = "relative")
net2 <- build_network(d2, method = "relative")
perm <- permutation(net1, net2, iter = 20, seed = 42)
print(perm)
summary(perm)
# Students are nested in teams, and Achiever is a team-level label:
# permute whole teams, not single students
net <- build_network(group_regulation_long, method = "relative",
actor = "Actor", action = "Action", time = "Time",
group = "Achiever")
permutation(net, iter = 20, actor = "Group", seed = 1)
Diagnose the effect of nesting on a permutation test
Description
permutation_diagnostics() shows what treating nested sequences as
independent costs a network comparison. It runs permutation() twice on
the same networks and seed: once shuffling single sequences, once with
actor, shuffling whole actors (the persons whose sessions the
sequences are, or the teams of students). It returns the two results
side by side, one row per compared pair or per edge, with the
intraclass correlation (ICC) and design effect that explain any
difference between them. It takes two transition networks, or every
pair of groups of a netobject_group.
A design effect near 1 and few changed edges say that the nesting
changes the comparison little. Where the two tests differ, the
actor-level one is the test that follows the nesting, as permutation()
sets out for nested data. The sections Nested data and actor and ICC
and design effect of permutation() define these quantities, and How
to read the result below says what each column shows.
Usage
permutation_diagnostics(
x,
y = NULL,
actor,
iter = 1000L,
alpha = 0.05,
level = c("overall", "edges"),
seed = NULL
)
Arguments
x |
The networks to compare: a |
y |
The |
actor |
The column identifying the actor each sequence belongs to,
as in |
iter |
The number of permutations for each of the two tests, at
least 2. Default |
alpha |
The significance level that counts an edge as significant,
between 0 and 1. The p-values are not adjusted for multiplicity.
Default |
level |
|
seed |
A seed for the shuffles, used by both tests, so the result
repeats exactly. Default |
Value
A data frame. With level = "overall", one row per compared
pair:
- pair
"<x> vs <y>", the names of the two groups ("x vs y"for two networks).- n_sequences, n_actors
The sequences and distinct actors in the pair.
- design
"between"(every actor in one group),"within"(every actor in both groups) or"mixed"; with severalactorlevels, one"<level>: <design> (<n> actors)"entry per level.- icc, icc_ci_lower, icc_ci_upper
How alike the sequences of one actor are: the jackknife bias-corrected ICC, as printed by
permutation(), with a 95% interval; with fewer than 3 actors the ICC is the uncorrected estimate and the interval isNA; the ICC isNAwhen no transition share varies.- deff_edges
The median over edges of the design effect, the ratio of the actor-level to the sequence-level null variance of the edge difference (Kish, 1965).
- deff_global
The same ratio for the global
Mstatistic.- p_global_sequence, p_global_actor
The permutation p-values of
Mwhen sequences or whole actors are reassigned.- sig_edges_sequence, sig_edges_actor
The number of edges with
p < alphaunder each test.- edges_changed
The number of edges significant under one test but not the other.
- min_p_actor
The smallest p-value the exact actor-level test can give: one over the number of distinct arrangements of the actors, or
1 / (iter + 1), whichever is larger.p_global_actorand the edge p-values are Monte Carlo estimates, so with few arrangements they can fall below it by chance.
With level = "edges", one row per edge present in either network, with
the columns pair, from, to, diff (the observed difference,
x - y), icc (the edge's ANOVA ICC, not bias-corrected; NA where
the share does not vary), null_sd_sequence and null_sd_actor (the
SD of the shuffled differences under each test), deff (NaN where
the edge difference never varies under either null), p_sequence,
p_actor and changed (whether the edge is significant under one test
only).
The ICC and design effects are those of the actor-level run, as
permutation() prints them when given actor; the p-values and
significance counts compare it with a separate ordinary run.
How to read the result
deff_edges,deff_globalThe design effect (Kish, 1965): actor-level over sequence-level null variance. 1 means the two shuffles give the same chance variation; above 1 the actor-level one varies more, below 1 less.
edges_changedEdges significant under one test but not the other. Edges with p-values close to
alphacan flip from Monte Carlo error alone; increaseiterbefore reading much into one or two.min_p_actorabovealphaToo few actors: the exact actor-level test cannot reject anything, and an actor-level p-value below
alphais Monte Carlo chance.
References
Efron, B., & Tibshirani, R. J. (1993). An Introduction to the Bootstrap. Chapman & Hall. (jackknife, ch. 11)
Kish, L. (1965). Survey Sampling. Wiley. (design effect)
Anderson, M. J., & ter Braak, C. J. F. (2003). Permutation tests for multi-factorial analysis of variance. Journal of Statistical Computation and Simulation, 73(2), 85-113.
See Also
Examples
# Students are nested in teams; Achiever is a team-level label.
# iter = 20 keeps the example fast; a real analysis uses 1000 or more.
net <- build_network(group_regulation_long, method = "relative",
actor = "Actor", action = "Action", time = "Time",
group = "Achiever")
permutation_diagnostics(net, actor = "Group", iter = 20, seed = 1)
head(permutation_diagnostics(net, actor = "Group", iter = 20,
level = "edges", seed = 1))
Compute the persistence landscape of a persistence diagram
Description
persistence_landscape() computes the persistence landscape (Bubenik
2015) of one homology dimension of a persistence diagram, evaluated on a
grid. Each (birth, death) pair contributes a tent function
\Lambda_{(b,d)}(t) = \max(0, \min(t - b, d - t)),
and the k-th landscape function \lambda^{(k)}(t) is the
k-th largest of \{\Lambda_{(b_i,d_i)}(t)\}_i at each
t. It takes a persistent_homology() result or a data frame of
persistence pairs.
At each filtration value t, a tent is the distance from t
to the nearer end of a feature's interval (0 outside it), so the first
landscape function follows the feature that t lies deepest
inside, the second the feature with the second largest tent, and so
on. This need not be the most persistent feature alive: a long-lived
feature near its birth or death can sit below a shorter one near its
midpoint. Landscapes
are stable: the sup-norm distance between two landscapes is at most the
bottleneck_distance() between their diagrams. They also live in a
Banach space, where they can be averaged (Bubenik 2015).
Essential classes are left out, because the tent of an infinitely lived
class is undefined on a finite grid: pairs with death = Inf (VR mode)
and pairs with death = 0 but birth > 0 (the clique-mode encoding of
an essential class) are dropped before the landscape is built. When no
finite pair remains in the requested dimension, every landscape
function is zero on the grid.
Usage
persistence_landscape(ph, k_max = 5L, dimension = 1L, t_grid = NULL)
## S3 method for class 'persistence_landscape'
print(x, ...)
## S3 method for class 'persistence_landscape'
plot(x, ...)
Arguments
ph |
The diagram: a |
k_max |
The number of landscape functions to compute, a positive
whole number. Functions beyond the number of pairs are zero. Default
|
dimension |
The homology dimension, a single non-negative whole
number. Default |
t_grid |
The filtration values to evaluate the landscape at.
Default |
x |
For the |
... |
Not used. |
Value
A persistence_landscape object. Printing it shows the
dimension, k_max, the grid range and the sup norm (largest value) of
each landscape function; plot() draws the functions as lines over
the grid. The object holds:
- landscape
A data frame with one row per landscape function and grid point, and the columns
k,tandvalue.- dimension
The homology dimension.
- k_max
The number of landscape functions.
- t_grid
The evaluation grid.
The print() method returns its input invisibly, and plot() a
ggplot object with one line per landscape function.
References
Bubenik, P. (2015). Statistical topological data analysis using persistence landscapes. Journal of Machine Learning Research 16, 77-102.
Examples
mat <- matrix(c(0, .6, .5, .6, 0, .4, .5, .4, 0), 3, 3)
rownames(mat) <- colnames(mat) <- c("A","B","C")
ph <- persistent_homology(mat, n_steps = 5)
pl <- persistence_landscape(ph, k_max = 3, dimension = 0)
Compute the persistent homology of a network
Description
persistent_homology() follows the holes of a network's simplicial
complex as the complex is grown edge by edge: each component, loop or
void is born when it first appears and dies when it is filled in, and the
result lists every such feature with its birth, death and persistence (how
long it lasts). Two filtrations are available:
type = "clique"A weighted clique filtration on similarities: edges enter from the strongest to the weakest, and a simplex enters at the smallest absolute weight among its edges, so the thresholds run from high to low.
type = "vr"A Vietoris-Rips filtration on a non-negative distance matrix: a simplex enters at the largest distance among its nodes, so the thresholds run from low to high.
max_scalecaps the distances considered.
A simplicial_complex from build_simplicial(type = "vr"), which stores
the scale at which each simplex enters, is also read directly.
Features with long persistence last over a wide range of thresholds;
features that die soon after they are born are commonly read as noise.
Essential features never die: the component that remains at the end, and
any hole that no simplex in the filtration fills. bottleneck_distance()
compares the diagrams of two networks, and persistence_landscape()
turns a diagram into functions that can be averaged.
Usage
persistent_homology(
x,
n_steps = 20L,
max_dim = 3L,
type = "clique",
max_scale = NULL
)
## S3 method for class 'persistent_homology'
print(x, ...)
## S3 method for class 'persistent_homology'
plot(x, combined = TRUE, ...)
Arguments
x |
The network: a square weight matrix (similarities for
|
n_steps |
The number of thresholds on which the Betti curve is
reported, a positive whole number. Default |
max_dim |
The highest feature dimension reported, a non-negative
whole number. Default |
type |
The filtration: |
max_scale |
For |
... |
For the |
combined |
For the |
Details
The persistence pairs come from the full reduction of the boundary
matrix over \mathbb{Z}/2 (Edelsbrunner, Letscher & Zomorodian,
2000): each feature is paired with the simplex whose entry creates it
(birth) and the simplex whose entry destroys it (death). Pairs born and
killed at the same value are dropped. The diagram is exact; n_steps
only sets the grid on which the Betti curve is reported.
In the clique filtration the weight matrix is made symmetric with the
larger absolute weight of the two directions, its diagonal is not read,
and every node enters at the largest weight. An essential feature has
death = 0 and persistence = birth; the Betti curve is read on
n_steps thresholds from the largest weight down to 1% of it. In the
Vietoris-Rips filtration the matrix is made symmetric with the larger
distance, every node enters at 0, and an essential feature has
death = Inf and persistence = Inf; the curve runs from 0 to the
largest entry value. The filtration holds simplices one dimension above
max_dim, so a feature of dimension max_dim can die (the Ripser
convention).
Value
A persistent_homology object. print() shows the threshold
range, the number of features per dimension and the three
longest-lived; plot() draws the Betti curve and the persistence
diagram; bottleneck_distance() and persistence_landscape() read it.
The object's fields:
- betti_curve
Data frame with one row per threshold and dimension:
threshold,dimensionandbetti, the number of features alive at that threshold.- persistence
Data frame with one row per feature, sorted by decreasing persistence:
dimension,birth,deathandpersistence. Essential features are included, withdeath = 0in the clique filtration anddeath = Infin the Vietoris-Rips one.- thresholds
The thresholds of the Betti curve.
- mode
"clique"or"vr".
The print() method returns its input invisibly. plot()
returns the drawn grid grob invisibly with combined = TRUE, and the
named list of two ggplots invisibly with combined = FALSE. The
diagram plots each feature's birth against its death; essential
features are drawn at the end of the filtration, at death = 0 in the
clique filtration and, for the Vietoris-Rips one, at the largest finite
value in the diagram or on the threshold grid.
References
Edelsbrunner, H., Letscher, D., & Zomorodian, A. (2000). Topological persistence and simplification. In Proceedings of the 41st Annual Symposium on Foundations of Computer Science, 454-463. Journal version: Discrete & Computational Geometry (2002) 28, 511-533.
Examples
mat <- matrix(c(0,.6,.5,.6,0,.4,.5,.4,0), 3, 3)
colnames(mat) <- rownames(mat) <- c("A","B","C")
ph <- persistent_homology(mat, n_steps = 10)
print(ph)
Plot state frequencies as treemaps or bars
Description
plot_state_frequencies() counts how often each state occurs in the
sequences behind a network and draws the shares, per group, as treemaps
or bars; it returns the chart together with the table of counts. It
takes a netobject, a netobject_group (one group per network), an
mcml (one group per cluster) or an htna network (one group per
actor). A single netobject is one group, "all", unless it carries
node groups, which then form the groups. Missing and empty cells are not
counted.
With style = "marimekko" (default), each group is a treemap whose
tiles have areas proportional to the states' shares within that group.
The groups of a netobject or netobject_group are panels of one plot,
with the states in the same order and colours in every panel. The actors
of an htna network and the clusters of an mcml usually have states
of their own, so each is drawn as a separate treemap with its own legend
(legend = "per_facet"). An mcml drawn with any other legend is a
single marimekko instead: one column per cluster, as wide as the
cluster's share of all events, with its states stacked by their share
within the cluster. With style = "bars", each group is a panel of
horizontal bars, one per state.
The shares describe how often states occur, not how they follow each
other. Two groups can have the same state mix and different
transitions; compare the networks for that, with permutation().
mosaic_plot() shows which cells of a netobject_group's
group-by-state table depart from independence.
Usage
plot_state_frequencies(x, ...)
## S3 method for class 'nestimate_facet_plot'
print(x, ...)
## S3 method for class 'nestimate_facet_list'
print(x, ...)
## S3 method for class 'netobject'
plot_state_frequencies(
x,
style = "marimekko",
metric = "prop",
label = "prop",
legend = "auto",
legend_dir = "auto",
legend_frame = "none",
sort_states = "frequency",
colors = NULL,
label_size = 3.5,
abbreviate = FALSE,
include_macro = FALSE,
combine = "auto",
ncol = NULL,
node_groups = NULL,
state_colors = NULL,
...
)
## S3 method for class 'htna'
plot_state_frequencies(
x,
style = "marimekko",
metric = "prop",
label = "prop",
legend = "auto",
legend_dir = "auto",
legend_frame = "none",
sort_states = "frequency",
colors = NULL,
label_size = 3.5,
abbreviate = FALSE,
include_macro = FALSE,
combine = "auto",
ncol = NULL,
node_groups = NULL,
state_colors = NULL,
...
)
## S3 method for class 'mcml'
plot_state_frequencies(
x,
style = "marimekko",
metric = "prop",
label = "prop",
legend = "auto",
legend_dir = "auto",
legend_frame = "none",
sort_states = "frequency",
colors = NULL,
label_size = 3.5,
abbreviate = FALSE,
include_macro = FALSE,
combine = "auto",
ncol = NULL,
node_groups = NULL,
state_colors = NULL,
...
)
## S3 method for class 'netobject_group'
plot_state_frequencies(
x,
style = "marimekko",
metric = "prop",
label = "prop",
legend = "auto",
legend_dir = "auto",
legend_frame = "none",
sort_states = "frequency",
colors = NULL,
label_size = 3.5,
abbreviate = FALSE,
include_macro = FALSE,
combine = "auto",
ncol = NULL,
node_groups = NULL,
state_colors = NULL,
...
)
## Default S3 method:
plot_state_frequencies(x, ...)
## S3 method for class 'state_freq'
print(x, digits = 1, max_states = 20L, ...)
## S3 method for class 'state_freq'
plot(x, ...)
Arguments
x |
The object to count: a |
... |
Not used: the |
style |
The chart. |
metric |
For |
label |
The text printed on each tile or bar, on one line:
|
legend |
Where the colour legend goes: |
legend_dir |
The direction of the legend's keys: |
legend_frame |
|
sort_states |
The order of the states in the legend, the tiles and
the bars: |
colors |
Deprecated name of |
label_size |
The size of the tile and bar labels; with
ggfittext installed, the largest size, as labels shrink to fit
their tiles. Default |
abbreviate |
Whether to shorten the state names with
|
include_macro |
For an |
combine |
With per-panel legends: |
ncol |
For a combined figure with per-panel legends: the number of
columns. Default |
node_groups |
A named character vector that maps states to broader
groups, such as |
state_colors |
Fill colours for the states, overriding the palette
attached to |
digits |
For |
max_states |
For |
Value
A state_freq object. Printing it shows the event totals per
group and the share of each state within its group, then draws the
chart; plot() draws the chart alone. state_distribution() of the
result returns the table as drawn, one row per group and state;
state_distribution() of the network gives
the same counts, with the full state names and, for
an mcml, without the macro group unless include_macro = TRUE.
The object holds the chart (a
ggplot; with per-panel legends either a combined figure, a gtable
of class nestimate_facet_plot, or a list of ggplots of class
nestimate_facet_list), the table (one row per group and state, with columns group,
state, count and proportion, the share within the group), and
the style, metric and source class of the call. The print()
methods return their input invisibly, plot() returns NULL
invisibly. Any other class raises an error, a tna model included;
draw a tna model with tna::plot_frequencies().
The state_freq object
In a knitr document, printing the object puts the table in the text and the chart in a figure of the chunk's size; a list of per-panel plots gives one figure per panel.
Examples
if (requireNamespace("ggplot2", quietly = TRUE)) {
data(group_regulation_long, package = "Nestimate")
nw <- build_network(group_regulation_long,
method = "relative", format = "long",
actor = "Actor", action = "Action",
order = "Time", group = "Course")
res <- plot_state_frequencies(nw)
print(res) # tidy frequency table in the console
plot(res) # ggplot chart
head(state_distribution(res))
}
Predict missing or future links in a network
Description
predict_links() scores every pair of nodes for how strongly the
network's structure suggests a link between them, with one or more
similarity indices: common neighbours, resource allocation, Adamic-Adar,
Jaccard, preferential attachment and Katz (Liben-Nowell & Kleinberg,
2007). It returns one row per pair and index, ranked within each index,
and a consensus ranking across the indices. It takes a netobject, a
cograph_network, a tna model or a square weight matrix, weighted or
binary, directed or undirected.
A high score says that a pair resembles linked pairs in the network's
structure (shared neighbours, busy endpoints, many connecting paths), not
that the link exists in the population or will form. The indices are
heuristics and often disagree; the consensus rank shows the pairs on which
they agree. How well an index recovers links is measured by scoring
held-out edges with evaluate_links(); pathways() writes the top
predictions as pathway strings.
Usage
predict_links(
x,
methods = c("common_neighbors", "resource_allocation", "adamic_adar", "jaccard",
"preferential_attachment", "katz"),
weighted = TRUE,
top_n = NULL,
exclude_existing = TRUE,
include_self = FALSE,
katz_damping = NULL
)
## S3 method for class 'net_link_prediction'
print(x, ...)
## S3 method for class 'net_link_prediction'
summary(object, ...)
Arguments
x |
The network: a |
methods |
The indices to compute, one or more of
|
weighted |
Whether common neighbours, resource allocation,
Adamic-Adar and Jaccard use the edge weights ( |
top_n |
The number of predictions kept per index, the highest
scores. Default |
exclude_existing |
Whether pairs that already have an edge are left
out of the predictions. Default |
include_self |
Whether self-pairs (a node with itself) are listed for
a directed network; an undirected network never lists them. All indices
score self-pairs 0. It also decides whether self-loops count in the
number of existing edges. Default |
katz_damping |
The attenuation factor |
... |
For the |
object |
For |
Details
Methods
- common_neighbors
The number of shared neighbours. For a directed network, shared out-neighbours plus shared in-neighbours, computed as
A %*% t(A) + t(A) %*% A.- resource_allocation
Zhou et al. (2009). Like common neighbours, but each shared neighbour z is weighted by
1/degree(z)(in- plus out-degree for a directed network). It penalises hubs and rewards rare shared connections.- adamic_adar
Adamic & Adar (2003). Like resource allocation, but weighted by
1/log(degree(z)), a milder penalty; a neighbour of degree 1 adds nothing.- jaccard
Shared neighbours divided by all neighbours of the two nodes. With
weighted = TRUEit is the weighted Jaccard (Ruzicka) index,\sum_z \min(|w_{iz}|, |w_{jz}|) / \sum_z \max(|w_{iz}|, |w_{jz}|), which equals the binary index on 0/1 weights and lies between 0 and 1. For a directed network, computed on the combined (out + in) neighbourhoods, each neighbour weighted by the larger of its two directions.- preferential_attachment
The source's out-degree times the target's in-degree (Barabasi & Albert, 1999): the "rich get richer" effect.
- katz
Katz (1953). A sum over all paths between the two nodes, damped exponentially by path length, computed by matrix inversion as
(I - beta * A)^{-1} - I. It reads the global structure. If the inversion fails, the series is truncated after six terms.
Every index is computed with matrix operations on the whole network at once.
Value
A net_link_prediction object. print() lists the top ten
predicted links (by consensus rank with several indices, by score with
one) and returns its input invisibly. summary() returns a data frame
with one row per index: method, n_predictions, and the score_mean,
score_sd, score_max and score_min of its predictions; an index
with no predictions (every possible link already exists) has
n_predictions = 0 and NA scores. evaluate_links() scores the
predictions against known edges, and pathways() writes them as pathway
strings. The object's fields:
- predictions
Data frame, one row per node pair and index:
from,to,method,score,existing(whether the pair already has an edge) andrank(pairs with the same score share the lowest of their ranks), sorted by score (highest first) within each index, tied pairs by name. An undirected network lists each pair once.- consensus
Data frame, one row per node pair:
from,to,avg_rank(the pair's mean rank over the indices that list it),n_methods(how many do) andconsensus_rank(shared by equalavg_ranks), ordered byavg_rank.NULLwhen only one index was computed.- scores
Named list of score matrices, one per index.
- adjacency
The 0/1 adjacency matrix of the input network.
- weights
The weight matrix of the input network.
- methods
The indices computed.
- nodes
The node names.
- directed, weighted
Whether the network was read as directed, and whether weights were used.
- n_nodes
The number of nodes.
- n_existing
The number of existing edges: non-zero cells of the adjacency matrix, each undirected edge counted once, self-loops counted only with
include_self = TRUE.
References
Liben-Nowell, D. & Kleinberg, J. (2007). The link-prediction problem for social networks. JASIST, 58(7), 1019–1031.
Zhou, T., Lu, L. & Zhang, Y.-C. (2009). Network topology and link prediction. European Physical Journal B, 71, 623–630.
Adamic, L. A. & Adar, E. (2003). Friends and neighbors on the Web. Social Networks, 25(3), 211–230.
Katz, L. (1953). A new status index derived from sociometric analysis. Psychometrika, 18(1), 39–43.
Jaccard, P. (1901). Etude comparative de la distribution florale dans une portion des Alpes et des Jura. Bulletin de la Societe Vaudoise des Sciences Naturelles, 37, 547–579.
Ioffe, S. (2010). Improved consistent sampling, weighted minhash and L1 sketching. IEEE International Conference on Data Mining, 246–255.
Barabasi, A.-L. & Albert, R. (1999). Emergence of scaling in random networks. Science, 286(5439), 509–512.
See Also
evaluate_links for prediction evaluation,
build_network for network estimation.
Examples
seqs <- data.frame(
V1 = c("A", "B", "C", "D", "A", "C", "E", "B"),
V2 = c("B", "C", "D", "E", "C", "E", "A", "D"),
V3 = c("C", "D", "E", "A", "D", "A", "B", "E")
)
net <- build_network(seqs, method = "relative")
pred <- predict_links(net)
print(pred)
summary(pred)
Compute the predictability of each node
Description
predictability() computes how well each node of an association network
is predicted by the others: the proportion of its variance explained
(R^2), with the root mean squared error (RMSE) of that prediction,
following Haslbeck & Waldorp (2018). It reads networks estimated with
method = "glasso", "pcor" or "cor", single, multilevel
(netobject_ml) or grouped (netobject_group). build_network()
stores the same R^2 values on these networks when
predictability = TRUE (the default), and cograph::splot() draws them
as a ring around each node.
R^2 says how much of a node's variance its connections in the
network account for; a low value leaves most of it to variables outside
the network or to noise. It is computed from the matrices estimated on
the sample, so it describes that sample. For "glasso" it reflects the
regularised estimate, and for "cor" it depends on which edges survive
threshold.
Usage
predictability(object, ...)
## S3 method for class 'netobject'
predictability(object, data = NULL, ...)
## S3 method for class 'netobject_ml'
predictability(object, ...)
## S3 method for class 'netobject_group'
predictability(object, ...)
## Default S3 method:
predictability(object, ...)
Arguments
object |
The network: a |
... |
Not used. |
data |
The variables the network was estimated from, used only for
the |
Details
For "glasso" and "pcor", R^2 comes from the estimated precision
matrix \Omega (the inverse of the correlation matrix, regularised
for "glasso"):
R^2_j = 1 - 1 / \Omega_{jj}
For "cor", it is the multiple R^2 of each node regressed on its
neighbours (the nodes it shares a non-zero edge with), computed from the
stored correlation matrix: 0 for a node without neighbours, the squared
correlation for a node with one. Values are clipped to [0, 1].
RMSE predicts each standardised variable from the others (for "cor",
from its neighbours) with the regression weights implied by the same
matrix, on the complete rows of the data, and reports the error on the
variable's original scale. For "cor", a node without neighbours has an
RMSE equal to its standard deviation (prediction by the mean), and a
singular correlation block of its neighbours gives an R^2 of 0 and
an RMSE of NA.
Value
A data frame with one row per node and the columns node (the
node label), R2 (between 0 and 1) and RMSE (NA when no data is
available). A netobject_ml gives a list of two such data frames,
between and within, and a netobject_group a named list of them,
one per group.
References
Haslbeck, J. M. B., & Waldorp, L. J. (2018). How well do network models predict observations? On the importance of predictability in network models. Behavior Research Methods, 50(2), 853–861. doi:10.3758/s13428-017-0910-x
Examples
set.seed(42)
mat <- matrix(rnorm(60), ncol = 4)
colnames(mat) <- LETTERS[1:4]
net <- build_network(as.data.frame(mat), method = "glasso")
predictability(net)
Prepare an event log for network estimation
Description
prepare() turns an event log (one row per event: the action, and
optionally who did it and when) into sequences, one row per session and
one column per position (T1, T2, ...). It parses the timestamps,
orders the events, splits each actor's events into sessions by explicit
session columns and by time gaps, and keeps every other column as one
row of metadata per session. build_network() runs the same preparation
itself when given action, with the same arguments, so prepare() is
for inspecting the sequences or passing them to the sequence verbs.
Usage
prepare(
data,
actor,
action,
time = NULL,
order = NULL,
session = NULL,
time_threshold = 900,
custom_format = NULL,
is_unix_time = FALSE,
unix_time_unit = c("seconds", "milliseconds", "microseconds"),
timezone = "UTC"
)
## S3 method for class 'nestimate_data'
print(x, ...)
Arguments
data |
The event log: a data frame with one row per event. |
actor |
The column, or columns, identifying who performed each event
(e.g. |
action |
The column holding each event's action (state or code). |
time |
The timestamp column. Default |
order |
The column that orders the events: with |
session |
The column, or columns, identifying explicit sessions
(e.g. |
time_threshold |
The longest gap, in seconds, between consecutive
events of one session; a longer gap starts a new session, numbered
|
custom_format |
A |
is_unix_time |
Whether |
unix_time_unit |
The unit of numeric timestamps. Default |
timezone |
The Olson time zone (see |
x |
For the |
... |
Not used. |
Details
Within each actor and session, events are sorted by time and then by
order. Sessions are identified by the observed combinations of the
actor and session values, so identifiers containing separator
characters stay distinct and high-cardinality identifiers cannot
overflow. A missing value in any of these columns raises an error of
class nestimate_bad_input: drop or relabel those events first.
Every other column is aggregated into the session metadata: numeric columns by their mean, other columns by their most frequent value. A tie goes to the tied value that occurs first in the session, and a message names the columns where that happened.
Value
A nestimate_data object. print() gives the numbers of
sessions and actions, the longest sequence, the number of actors when
actor was given and whether times were parsed, and returns its input
invisibly. extract_sequences(), sequence_patterns() and
sequence_metrics() read it directly. It holds:
- sequence_data
The sequences as a data frame: one row per session, one column per position (
T1,T2, ...), padded withNA.- long_data
The events in their sorted order, with the parsed time and the working columns that identify each event's session and position (
.session_id,.session_label,.sequence, ...).- meta_data
One row per session, in the row order of
sequence_data:.session_id,.session_label, the actor column (with several, their combined label.actor, joined by"-", or by the first of"|"," | "," / "," :: "that keeps distinct actors apart when values contain"-"), the session column(s) under their own names, and every other column aggregated per session.- time_data
The parsed times in the layout of
sequence_data(columnstime_T1,time_T2, ...), intimezone(or the zone of a date-timetimecolumn), orNULLwithouttime.- statistics
A list with
total_sessions,total_actionsandmax_sequence_length, plusunique_actors(distinct combinations of theactorcolumns) only whenactorwas given (without it, every event belongs to one actor).
See Also
Examples
set.seed(1)
df <- data.frame(
student = rep(1:3, each = 5),
code = sample(c("read", "write", "test"), 15, replace = TRUE),
timestamp = seq.POSIXt(as.POSIXct("2024-01-01"), by = "min", length.out = 15)
)
prepared <- prepare(df, actor = "student", action = "code",
time = "timestamp")
prepared
# build_network() runs the same preparation itself
net <- build_network(df, actor = "student", action = "code",
time = "timestamp", method = "relative")
net
Prepare sequence data for the tna package
Description
prepare_for_tna() returns the sequence columns of a data set as a wide
data frame for tna::tna() and related functions: one row per sequence
and the position columns V1, V2, ... in numeric order, with factors
turned into character. Long input is converted with long_to_wide()
first, padding shorter sequences with NA. Every other column (an id,
metadata) is dropped.
Usage
prepare_for_tna(
data,
type = c("sequences", "long", "auto"),
state_names = NULL,
id_col = "Actor",
time_col = "Time",
action_col = "Action",
validate = TRUE
)
Arguments
data |
A data frame of sequences: wide, with position columns named
|
type |
How to read |
state_names |
The expected states, used with |
id_col |
The column identifying sequences in long data. Default
|
time_col |
The column ordering the actions in long data. Default
|
action_col |
The column holding the actions in long data. Default
|
validate |
Whether to check the states against |
Value
A data frame with one row per sequence and only the position
columns V1, V2, ..., in numeric order, holding character states (or
the original type for non-factor columns), with no row names.
See Also
wide_to_long, long_to_wide for
format conversions.
Examples
# From wide format sequences
sequences <- data.frame(
V1 = c("A","B","C","A"), V2 = c("B","C","A","B"),
V3 = c("C","A","B","C"), V4 = c("A","B","A","B")
)
tna_data <- prepare_for_tna(sequences, type = "sequences")
Describe the q-connectivity of a simplicial complex
Description
q_analysis() describes how the maximal simplices of a simplicial complex
(those not contained in a larger one) hang together, after Atkin (1974).
Two maximal simplices are q-near when they share a face of dimension at
least q (q + 1 shared nodes), and q-connected when a chain of q-near
simplices joins them. The result has two parts:
-
Q-vector:
Q_q, the number of q-connected components among the maximal simplices of dimension at least q, for each q from the largest simplex dimension down to 0. Simplices of lower dimension do not exist at level q and are not counted. -
Structure vector: here the dimension of the largest simplex each node belongs to. (Atkin uses "structure vector" for the Q-vector itself; the name is kept for compatibility.)
A Q-vector of 1 at every level means the maximal simplices stay in one
piece however many shared nodes are required. Requiring more shared
nodes splits the complex more, but fewer simplices take part at higher
q, so the count can rise or fall with q; print() reports the lowest
level at which there is more than one. Like
the complex itself, the vectors depend on the threshold or pathways
build_simplicial() was given.
Usage
q_analysis(sc)
## S3 method for class 'q_analysis'
print(x, ...)
## S3 method for class 'q_analysis'
plot(x, combined = TRUE, ...)
Arguments
sc |
A |
x |
For the |
... |
For the |
combined |
For the |
Value
A q_analysis object. print() shows the components at each
level, the level at which the complex first splits and the structure
vector; plot() draws the two vectors. The object's fields:
- q_vector
Named integer vector, one entry per level from the highest down (
q_2,q_1,q_0for a complex of dimension 2): the number of q-connected components at that level.- max_q
The largest simplex dimension, the highest level.
- structure_vector
Named integer vector, one entry per node: the dimension of the largest simplex containing it.
The print() method returns its input invisibly. plot()
returns the drawn grid grob invisibly with combined = TRUE, and the
named list of two ggplots invisibly with combined = FALSE.
References
Atkin, R. H. (1974). Mathematical Structure in Human Affairs.
Examples
mat <- matrix(c(0,.6,.5,.6,0,.4,.5,.4,0), 3, 3)
colnames(mat) <- rownames(mat) <- c("A","B","C")
sc <- build_simplicial(mat, threshold = 0.3)
q_analysis(sc)
Register a network estimator
Description
register_estimator() adds an estimator function to the registry that
build_network() reads, so that build_network(data, method = name) calls
it the way it calls a built-in method; the package registers its fifteen
built-in methods with this function when it loads. A name already in the
registry is replaced, built-ins included, without a message.
list_estimators() shows what is
registered and remove_estimator() takes
an entry out.
A name that build_network() maps to a different built-in method (an
alias such as "tna" or "ebicglasso") is resolved to that method before
the registry is read, so an estimator registered under it is never called;
pick a name that is not an alias.
Usage
register_estimator(name, fn, description, directed)
Arguments
name |
The name the estimator is called by, as |
fn |
The estimator function. Its first argument is |
description |
A short description of the estimator, a single string,
shown by |
directed |
Whether the estimator produces directed networks, |
Details
build_network() calls the function as fn(data = data, ...), where ...
holds the params list, the further arguments given to build_network()
and a format setting, which is why fn must accept .... When actor
names a column of wide or association data (long data is prepared by
build_network() itself) and fn has an id_col argument (or, failing
that and for data that is not one-hot, an id argument), the actor
column is passed under that name unless params already sets it. Scaling,
thresholding and the edge list are then applied to the returned matrix,
as for a built-in method.
Besides matrix, nodes and directed, the returned list may hold
cleaned_data, the data frame the network was estimated from, which
build_network() splits into the network's data and metadata fields;
any other named element is copied onto the netobject, replacing a field
of the same name. A return value without matrix, nodes or directed
makes build_network() stop with an error.
Value
NULL, invisibly. The estimator is added to the registry as a
side effect.
Note
The idiographic package exports a function with the same
name. With both packages attached, the one attached last masks the
other; write Nestimate::register_estimator() to call this one.
See Also
get_estimator, list_estimators,
remove_estimator, build_network
Examples
my_fn <- function(data, ...) {
m <- cor(data)
diag(m) <- 0
list(matrix = m, nodes = colnames(m), directed = FALSE)
}
register_estimator("my_cor", my_fn, "Custom correlation", directed = FALSE)
df <- data.frame(A = rnorm(20), B = rnorm(20), C = rnorm(20))
net <- build_network(df, method = "my_cor")
remove_estimator("my_cor")
Remove a registered estimator
Description
remove_estimator() takes an estimator out of the registry, so
build_network() no longer finds it by name. Built-ins can be removed
too; they come back when the package is loaded again. A name that is not
registered raises an error.
Usage
remove_estimator(name)
Arguments
name |
The registered name of the estimator to remove, a single string. |
Value
NULL, invisibly. The entry is removed from the registry as a
side effect.
Note
The idiographic package exports a function with the same
name. With both packages attached, the one attached last masks the
other; write Nestimate::remove_estimator() to call this one.
See Also
register_estimator, list_estimators
Examples
register_estimator("test_est", function(data, ...) diag(3),
description = "test", directed = FALSE)
remove_estimator("test_est")
Rename the networks of a network group
Description
rename_models() replaces the names of the networks in a
netobject_group and returns the group with nothing else changed. The
names label every later report (print methods, plot panels, bootstrap
and permutation output), so this is the step that turns the generic
labels build_network() gives clusters ("Cluster 1", "Cluster 2")
into meaningful ones ("High engagement", "Low engagement") once it is
known what each cluster represents. It is the Nestimate counterpart of
tna::rename_groups().
Usage
rename_models(x, new_names)
## S3 method for class 'netobject_group'
rename_models(x, new_names)
## Default S3 method:
rename_models(x, new_names)
Arguments
x |
A |
new_names |
The new names, a character vector in the order of the
networks in |
Value
An object of the same class and length as x, its networks and
attributes (such as group_col) unchanged and its names replaced by
new_names.
Examples
grp <- build_network(group_regulation_long, method = "tna",
actor = "Actor", action = "Action", time = "Time",
group = "Achiever")
names(grp)
names(rename_models(grp, c("High achievers", "Low achievers")))
Compare subsequence patterns between groups
Description
sequence_compare() compares how often short subsequences occur in two
or more groups of sequences. For each pattern length in sub it counts
every k-gram (a run of k consecutive states, such as "A->B->C") in
each group, keeps the patterns that are frequent enough in every group,
and returns a net_sequence_comparison whose pattern table has one row
per pattern with its count, proportion and standardised residual in each
group and, optionally, a permutation or chi-square test of whether its
frequency differs between the groups. It takes a grouped network, a
single network or wide sequences with a grouping.
A residual says how far a group's count of a pattern lies from the count
expected if pattern and group were independent, in approximately
standard-normal units (Haberman, 1973); a positive value means the
pattern is more frequent in that group than independence predicts. The
p-values are adjusted across every pattern tested. The permutation test
treats the sequence as the
unit, while the chi-square test treats every occurrence as independent,
which overstates the evidence when occurrences within a sequence depend
on each other (see Details). Patterns of different lengths overlap
(each 3-gram contains two 2-grams), so their tests are not independent of
each other. sequence_patterns() with group asks the related question
of whether a pattern is present in more sequences of one group.
Usage
sequence_compare(
x,
group = NULL,
sub = 3:5,
min_freq = 5L,
test = c("permutation", "chisq", "none"),
iter = 1000L,
adjust = "fdr",
actor = NULL
)
## S3 method for class 'net_sequence_comparison'
print(x, n = 10L, digits = 2L, ...)
## S3 method for class 'net_sequence_comparison'
summary(object, format = c("wide", "long"), ...)
## S3 method for class 'net_sequence_comparison'
plot(
x,
top_n = 10L,
style = c("auto", "pyramid", "heatmap"),
sort = c("statistic", "frequency"),
alpha = 0.05,
show_residuals = FALSE,
...
)
Arguments
x |
The sequences:
Every input except a |
group |
The group of each sequence: the name of a column of a data
frame or matrix |
sub |
The pattern lengths to count, positive whole numbers.
Lengths longer than the sequences are dropped, and an error is raised
when none remains. Default |
min_freq |
The smallest count a pattern must reach in every group
to be kept, a positive whole number; when no pattern of any length
reaches it, an error is raised. Default |
test |
The inference: |
iter |
The number of permutations for |
adjust |
The p-value adjustment, any method of |
actor |
The column identifying the actor each sequence belongs to,
or several columns for nested levels, outermost first
( |
n |
For |
digits |
For |
... |
Not used. |
object |
For the |
format |
For |
top_n |
For |
style |
For |
sort |
For |
alpha |
For the pyramid: the significance level for the p-value
labels. Patterns with |
show_residuals |
For the pyramid: whether to print each bar's
standardised residual inside it. Default |
Details
The standardised residuals come from the 2 x G table of the pattern's
counts against the counts of all other k-grams of the same length in
each group, with the formula
(o - e) / sqrt(e * (1 - r/N) * (1 - c/N)). They are always
computed, whatever test is. A k-gram that spans a missing position is
not counted.
test chooses the inference:
"permutation"Shuffles the group labels across sequences
itertimes and recomputes, for each pattern, the Euclidean norm of its row of differences between observed and expected counts in the patterns-by-groups table of every pattern observed at that length (expected under independence), whether or notmin_freqkeeps it, so the filter does not change the null distribution of a reported pattern. It asks whether the pattern's distribution is associated with group membership at the level of the sequence, which respects the sequence as the unit of analysis but has little power when there are few sequences. The p-value is(b + 1) / (iter + 1), wherebcounts the permutations with a statistic at least as large as the observed one, so it cannot fall below1 / (iter + 1). The effect size is the observed statistic minus the mean of the permuted ones, divided by their standard deviation (taken as 1 when the permuted statistics do not vary; withiter = 1the effect size isNA, since at least two permutations are needed). The shuffles use R's random number generator: callbase::set.seed()first for reproducible p-values."chisq"Runs
stats::chisq.test()on each pattern's 2 x G table (with Yates' continuity correction when there are two groups). It asks whether the groups' streams of k-grams produce the pattern at different rates, treating every occurrence as an independent event: it is fast and has power with few sequences, but the independence it assumes is optimistic when sequences are strongly autocorrelated."none"No test; the counts, proportions and residuals only.
The p-values are adjusted once across all patterns of all lengths, with
stats::p.adjust().
Value
A net_sequence_comparison object. print() shows the numbers
of patterns and groups, the settings and the first n patterns, one
row per pattern and group, rounded, and returns its input invisibly;
summary() returns the pattern table, a data frame with one row per
pattern (format = "long": one row per pattern and group); plot()
draws the residuals of the top patterns (see Plot styles). The object
holds:
- patterns
The pattern table, one row per k-gram kept. Always:
pattern,length, and per groupfreq_<group>(the count),prop_<group>(the count as a share of all k-grams of that length in the group, rare ones included) andresid_<group>(the standardised residual). Withtest = "permutation"alsoeffect_sizeandp_value; withtest = "chisq",statisticandp_value. The p-values are adjusted. Rows are ordered by ascendingp_value(ties by the larger absolute effect size, or the larger statistic) when a test was run, and by descending largest absolute residual otherwise.- groups
The group names, sorted.
- n_patterns
The number of rows of the pattern table: the patterns that reach
min_freqin every group.- params
The settings used:
sub(after dropping lengths longer than the sequences),min_freq,test,iterandadjust; withactorandtest = "permutation"alsoactor(the column name),n_actors(the number of distinct actors among the sequences with a group) anddesign("between"when every actor lies in one group,"within"when every actor lies in several,"mixed"otherwise). With severalactorlevels,n_actorscounts the innermost level,designreads"<level>: <design> (<n> actors)"for every level, andactor_levelsis a data frame with one row per level:level,n_actors,n_pureandn_crossed(the units the shuffle met at that level, inside crossed units above, in one group or in several) anddesign("not opened"when no unit above was crossed).
Nested data and actor
The permutation test treats every sequence as exchangeable. When several
sequences come from the same actor (sessions of one student, students of
one team), they resemble each other, and shuffling single sequences
understates how much the pattern counts vary by chance: when the groups
are made of different actors, the test then rejects too often. actor
names the column identifying the actor of each sequence, and the shuffle
respects it, as in permutation() (Good, 2005; Anderson & ter Braak,
2003): an actor whose sequences all lie in one group keeps them together
and moves as a whole, its group label shuffled among the other such
actors; an actor with sequences in several groups (a within-actor design,
such as pre and post sessions of each student) has its labels shuffled
among its own sequences only, so it keeps its number of sequences in each
group. Mixed designs combine the two. Use it whenever the groups are made
of different actors; for groups within actors it costs little. The
observed counts, proportions and residuals do not change; only the
p-values and effect sizes do. Sequences with a missing group keep it.
With few actors there are few distinct ways to shuffle them, and a
warning of class nestimate_few_actors is raised when no p-value could
fall below 0.05.
Several columns, outermost first (actor = c("Group", "Student")), are
nested levels, the unit at each level being the combination of its column
with the ones before it. The labels are then shuffled at the level where
they are assigned, within the units above it, as in permutation(): units
whose sequences all lie in one group exchange their labels with the other
such units of the same parent (all top-level units at the first level),
each moving whole; a unit with sequences in several groups is opened at
the next level, and inside such a unit of the last level single sequences
exchange labels. One column runs exactly the one-level scheme above.
Plot styles
plot() draws the standardised residuals of the top top_n patterns,
prints the plot and returns the ggplot invisibly (NULL, with a
message, when there are no patterns). style = "auto" (the default)
picks the style from the number of groups:
"pyramid"Back-to-back bars of each pattern's proportion in the two groups, each bar shaded by that group's standardised residual (the colour saturates at plus or minus 3), with the (adjusted) p-value in the gap between the bars when a test was run. Needs exactly 2 groups.
"heatmap"One tile per pattern and group, coloured by the standardised residual (the colour saturates at plus or minus 3) and labelled with its value. Works for any number of groups.
The residuals are filled whatever test was chosen, so both styles work
after test = "none".
References
Anderson, M. J., & ter Braak, C. J. F. (2003). Permutation tests for
multi-factorial analysis of variance. Journal of Statistical
Computation and Simulation, 73(2), 85-113. (the actor shuffle)
Good, P. (2005). Permutation, Parametric, and Bootstrap Tests of
Hypotheses (3rd ed.). Springer. (the actor shuffle)
Haberman, S. J. (1973). The analysis of residuals in cross-classified tables. Biometrics, 29(1), 205–220. (standardised residuals)
Benjamini, Y. & Hochberg, Y. (1995). Controlling the false discovery rate.
Journal of the Royal Statistical Society B, 57(1), 289–300.
(the default adjust = "fdr")
Examples
set.seed(1)
seqs <- data.frame(
V1 = sample(LETTERS[1:4], 60, TRUE),
V2 = sample(LETTERS[1:4], 60, TRUE),
V3 = sample(LETTERS[1:4], 60, TRUE),
V4 = sample(LETTERS[1:4], 60, TRUE)
)
grp <- rep(c("X", "Y"), 30)
net <- build_network(seqs, method = "relative")
res <- sequence_compare(net, group = grp, sub = 2:3, test = "chisq")
# Students are nested in teams, and Achiever is a team-level label:
# shuffle whole teams, not single students
net <- build_network(group_regulation_long, method = "relative",
actor = "Actor", action = "Action", time = "Time",
group = "Achiever")
set.seed(1)
sequence_compare(net, sub = 2, iter = 20, actor = "Group")
Compute descriptive indices for each sequence
Description
sequence_metrics() computes descriptive indices for every sequence and
returns one row per sequence: length and validity, composition and
diversity, spells, transitions, the fate of the initial state, the
dominant and emergent states, cyclic recurrence and a composite
complexity index, plus the integrative potential of a set of favourable
states when favorable is given. It reads any input
extract_sequences() reads: a wide table of positions, an event log, the
output of prepare(), a sequence network or group of networks, or a
tna model. The indices are those of codyna::sequence_indices(), with
three corrections listed under Details.
The indices describe each sequence as it was observed, and several of
them (spells, transitions, recurrence) rest on few positions in a short
sequence; read them beside valid_n. Because there is one row per
sequence, the result can be summarised, plotted or used as predictors;
sequence_patterns() and pattern_outcome() look at which subsequences
recur and how they relate to an outcome.
Usage
sequence_metrics(
x,
favorable = NULL,
omega = 1,
meta = FALSE,
cols = NULL,
actor = NULL,
action = NULL,
time = NULL,
group = NULL,
indices = NULL,
iter = 1000L,
adjust = "BH",
format = c("long", "wide"),
...
)
## S3 method for class 'net_sequence_metrics'
print(x, n = 10L, digits = 2L, ...)
## S3 method for class 'net_sequence_metrics'
summary(object, ...)
## S3 method for class 'net_sequence_metrics'
x[i, j, ...]
Arguments
x |
The sequence data, in any form |
favorable |
The favourable states; giving them adds
|
omega |
The exponent of the position weights in
|
meta |
Whether to put each sequence's covariates (actor, session,
group, metadata) before the indices. Default |
cols |
The state columns of a wide data frame, as in
|
actor, action, time |
The actor, action and timestamp columns of a
long event log; setting |
group |
A covariate of the sequences holding each sequence's group:
for a grouped network its group column (for example |
indices |
The indices to return, by name (for example
|
iter |
The number of permutations of the group comparison, a whole
number of at least 1. Default |
adjust |
The method of |
format |
The layout of a group comparison: |
... |
Further arguments passed to |
n |
For |
digits |
For |
object |
For |
i, j |
For |
Details
Positions after a sequence's last observed state are not part of it;
p below is the position of the last observed state.
- valid_n, valid_proportion
The number of observed states, and their share of the first
ppositions.- unique_states
The number of distinct states.
- mean_spell_duration, max_spell_duration
The mean and the longest run of one state.
- longitudinal_entropy
The Shannon entropy of the state proportions, divided by the log of the number of states in the data (0 to 1; 0 when the data hold one state).
- simpson_diversity
One minus the sum of squared proportions.
- self_loop_tendency, transition_rate
The share of transitions (pairs of adjacent observed states) that repeat the state, and the share that change it; the two sum to 1.
- transition_complexity
The number of distinct state-changing transitions, as a share of the
a(a - 1)possible ones, whereais the number of states in the data;NAwhen the data hold one state.- initial_state_persistence
The length of the opening spell as a share of
p.- initial_state_proportion
The share of the observed states that are the first state.
- initial_state_influence_decay
The share of the first third spent in the first state minus the share of the last third.
- cyclic_feedback_strength
The largest share, over lags of 2 or more, of positions whose state recurs that many steps later.
- first_state, last_state, dominant_state, dominant_proportion, dominant_max_spell
The opening and closing states; the most frequent state (ties go to the state that sorts first), its share and its longest spell.
- emergent_state, emergent_state_persistence, emergent_state_proportion
A state that settles in later, its spell and its share;
NAwhen there is none. The candidates are a spell of at least 3 that outlasts the dominant spell, the dominant state when it is not the first and has a spell of at least 3, and a return to the first state in a spell of at least 3 and more than half the opening one; the longest of them is taken.- integrative_potential
With
favorable: the position-weighted share of favourable states over the observed positions, with weightsposition^omega(Brzinsky-Fay 2018).- complexity_index
0.4 * longitudinal_entropy + 0.4 * transition_rate + 0.2 * min(CV of spell durations, 1); 0 for a sequence of one spell (one state, no change). This is codyna's composite, not the complexity index of Gabadinho et al. (2011) thatTraMineR::seqici()computes.
Missing values: a missing position is not an observation. The first
state is the first observed one, a missing position inside a sequence
ends a spell, and a pair of states across it is not a transition.
Indices that are undefined for a sequence (for example a rate with no
transition) are NA; a sequence with no observed state has
valid_n and unique_states 0 and every other index
NA. On sequences without
internal gaps the indices shared with TraMineR (seqindic(),
seqistatd(), seqdur(), seqintegr()) agree exactly;
at an internal gap TraMineR joins the states on either side into one
sequence, so spells and transitions differ there.
Corrections relative to codyna::sequence_indices() 1.0.0, which
otherwise agrees value for value: dominant_max_spell is computed
per sequence (codyna reports the last sequence's value for every row);
longitudinal_entropy is normalised by the log of the number of
states (codyna counts NA as one when the data have missing
values); and complexity_index uses the normalised entropy once
(codyna divides it by the log of the number of states a second time) and
is 0, not NA, for a single spell.
Leading and internal missing values follow the rule above, where codyna
reads position 1 as the first state and counts missing positions as
unfavourable and as possible transitions.
Value
A data frame with one row per sequence, in the order of
extract_sequences(), and the columns described in Details
(integrative_potential only with favorable). With meta = TRUE,
the input's covariate columns, if it has any, come first.
With group, a data frame of class c("net_sequence_metrics", "data.frame") with one row per numeric index and group: index,
group, n (the group's sequences with a value of the index), mean
and sd; then the index's comparison, which repeats on each of its
rows: with two groups difference (the second group's mean minus the
first's, in sorted order), hedges_g and its 95% interval g_lower,
g_upper; for any number of groups eta_squared, the one-way
statistic (F), the permutation p_value and the adjusted p_adj.
With format = "wide", one row per index with n_<group>,
mean_<group> and sd_<group> columns instead. The settings are
attributes (groups, group, actor, iter, adjust, format,
n_indices). print() shows the first n indices, rounded;
summary() returns the whole table as a plain data frame, and a subset
is a plain data frame.
Comparing groups
For each numeric index, the groups are compared with the one-way F
statistic, which for two groups is the square of the t statistic. Its
p-value is (b + 1) / (iter + 1), where b counts the permutations of
the group labels whose F is at least the observed one (Good, 2005); call
base::set.seed() first for reproducible p-values. A sequence with a
missing value of an index (a one-state sequence has no transition rate)
takes no part in that index. With actor, the labels are shuffled within
each actor whose sequences are in several groups and between the actors
whose sequences are all in one group, as in sequence_compare(). With
two groups, hedges_g is the standardised mean difference corrected for
small-sample bias, with an interval from its normal approximation
(Hedges, 1981). eta_squared is the share of the index's variance
between the groups.
References
Saqr, M., Tikka, S., & López-Pernas, S. (2026). codyna: Complex Dynamic Systems. R package version 1.0.0.
Brzinsky-Fay, C. (2018). Unused resources: Sequence and trajectory indicators. International Symposium on Sequence Analysis and Related Methods, Monte Verità.
Good, P. (2005). Permutation, parametric and bootstrap tests of hypotheses. Springer. doi:10.1007/b138696
Hedges, L. V. (1981). Distribution theory for Glass's estimator of effect size and related estimators. Journal of Educational Statistics, 6(2), 107-128. doi:10.3102/10769986006002107
Gabadinho, A., Ritschard, G., Müller, N. S., & Studer, M. (2011). Analyzing and visualizing state sequences in R with TraMineR. Journal of Statistical Software, 40(4), 1-37. doi:10.18637/jss.v040.i04
See Also
sequence_patterns, extract_sequences
Examples
head(sequence_metrics(trajectories))
head(sequence_metrics(trajectories, favorable = "Active"))
# compare the indices of the first and second halves of each session
halves <- mark_phases(human_long, actor = "session_id",
time = "order_in_session",
labels = c("early", "late"))
net <- build_network(halves, actor = "session_id", action = "cluster",
group = "phase", method = "relative")
set.seed(1)
sequence_metrics(net, iter = 19)
Discover sequential patterns
Description
sequence_patterns() finds the ordered patterns of states that occur in
a set of sequences and returns one row per pattern with how often it
occurs, how many sequences contain it, and its lift. It reads sequences
in every form extract_sequences() accepts, and finds three kinds of
pattern:
"ngram"Contiguous runs of
lenstates, e.g.A->B->C."gapped"Two states separated by
gappositions of any state, e.g.A->*->B(gap 1) orA->**->B(gap 2)."repeated"Runs of
lenidentical states, e.g.A->A->A.
A pattern template searches for the instances of one pattern instead,
and group adds a test of whether the share of sequences containing a
pattern differs between groups (see Group test).
Support and lift describe the sequences at hand. A lift above 1 says the
states of a pattern occur in this order in more sequences than their
separate presence predicts; it does not account for the transition
structure, so a pattern that the transition probabilities make likely
can have a lift above 1. Many patterns are searched at once, so read
the group test's p_adj, not p_value, and its effect sizes beside
them. To relate patterns to an outcome, use pattern_outcome(); to
compare how often each run of states occurs in each group,
sequence_compare().
Usage
sequence_patterns(
x,
type = c("ngram", "gapped", "repeated"),
len = 2:5,
gap = 1:3,
min_freq = 2,
min_support = 0.01,
start = NULL,
end = NULL,
contain = NULL,
pattern = NULL,
group = NULL,
reference = NULL,
adjust = "BH",
top = NULL,
cols = NULL,
actor = NULL,
action = NULL,
time = NULL,
format = c("long", "wide"),
...
)
## S3 method for class 'net_sequence_patterns'
print(x, n = 10L, digits = 2L, ...)
## S3 method for class 'net_sequence_patterns'
summary(object, ...)
## S3 method for class 'net_sequence_patterns'
x[i, j, ...]
Arguments
x |
The sequences, in any form |
type |
The kind of pattern to find: |
len |
The pattern lengths, in states, for |
gap |
The gap sizes, in positions, for |
min_freq |
The fewest times a pattern must occur to be kept, at
least 1. Default |
min_support |
The smallest share of sequences that must contain a
pattern for it to be kept, between 0 and 1. Default |
start, end |
States a pattern must begin ( |
contain |
States a pattern must include, one of them at least.
Default |
pattern |
A template to search for instead of discovering all
patterns. Each |
group |
The grouping of the sequences for the group test: the name
of a column stored with them (a covariate of a wide data frame or long
event log, or of a network's metadata), or a vector with one value per
sequence. A |
reference |
For two groups: the reference group, so the odds ratio
is that of the other group. Default |
adjust |
The multiplicity correction of the group test's p-values,
one of |
top |
The number of rows to return, a positive whole number: the
first in the output order. Default |
cols |
The state columns of a wide data frame, as in
|
actor, action, time |
The actor, action and timestamp columns of a
long event log; setting |
format |
With |
... |
Further arguments passed to |
n |
For |
digits |
For |
object |
For |
i, j |
For |
Details
support is the share of sequences that contain the pattern at least
once. lift compares it with the support expected if the states in the
pattern appeared in sequences independently:
support / prod(state_support), where the support of a state is the
share of sequences in which it occurs and wildcard positions are left
out.
A window that contains a missing value, at a fixed or a wildcard position, is skipped, so a pattern never spans a gap or the end of a sequence.
proportion is computed over all patterns of the same length before
min_freq, min_support, start, end and contain are applied, so
it does not change with the filters. Counts, support and lift agree with
codyna::discover_patterns(), which computes proportion after the
filters instead.
Value
A data frame with one row per pattern, ordered by support
(then occurrences, then pattern):
- pattern
The states joined by
"->";*marks a wildcard position.- length
The number of positions the pattern spans, gaps included.
- occurrences
The number of times it occurs.
- proportion
occurrencesas a share of all patterns of the same length.- n_sequences
The number of sequences that contain it.
- support
n_sequencesdivided by the number of sequences.- lift
Support relative to the independent presence of its states.
With group, a data frame of class c("net_sequence_patterns", "data.frame") with one row per pattern and group: the columns above,
then group and group_support (the share of the group's sequences
that contain the pattern); then the pattern's test, which repeats on
each group's row: odds_ratio, or_lower and or_upper for two
groups, or chisq and cramers_v for more; then p_value and
p_adj. Patterns are ordered by p_value (then support). With
format = "wide", one row per pattern with a support_<group> column
per group instead. The settings are attributes (group, groups,
n_patterns, format, test, adjust). print() shows the first
n patterns, rounded; summary() returns every row as a plain data
frame, and a subset is a plain data frame.
A state name that contains "->" or consists only of asterisks
(reserved for wildcards) raises an error of class
nestimate_bad_input.
Group test
With group, each pattern's presence (in a sequence or not) is
cross-tabulated against the group. For two groups, Fisher's exact test
gives the p-value, the conditional maximum-likelihood odds ratio of
containing the pattern in the non-reference group, and its 95%
confidence interval. A pattern that occurs in one group only has an
infinite (or zero) odds ratio, with a finite lower (or upper) limit; a
pattern present in every sequence has none (NA). For three or more
groups, the Pearson chi-square of the presence-by-group table gives the
p-value (G - 1 degrees of freedom), with Cramér's V as the
effect size. Unlike a comparison of counts against an equal split, both
tests account for unequal group sizes. The p-values are adjusted with
adjust over all patterns that pass the filters, before top is
applied, and the rows are ordered by p_value.
References
Agrawal, R., & Srikant, R. (1995). Mining sequential patterns. Proceedings of the Eleventh International Conference on Data Engineering, 3–14.
Fisher, R. A. (1935). The logic of inductive inference. Journal of the Royal Statistical Society, 98(1), 39–82.
See Also
pattern_outcome, sequence_compare
Examples
sequence_patterns(trajectories, len = 2:3, top = 10)
sequence_patterns(trajectories, type = "gapped", gap = 1)
sequence_patterns(trajectories, type = "repeated", len = 3:5,
start = "Disengaged")
sequence_patterns(group_regulation_long, actor = "Actor",
action = "Action", time = "Time", len = 2,
group = "Achiever", top = 10)
sequence_patterns(trajectories, pattern = "Active->*->Disengaged")
Draw a sequence index plot, heatmap or distribution plot
Description
sequence_plot() draws categorical sequences: one row per sequence and
one coloured cell per time point, or the share of sequences in each state
at every time point. Three views share one call:
-
type = "heatmap"(default): a dense carpet in a single panel, rows ordered bysortor a dendrogram. -
type = "index": the same layout with optional thin gaps between rows and no dendrogram, split into one panel per group (group, or the clusters of a clustering) on anncolxnrowgrid. -
type = "distribution": the stacked state distribution over time, drawn bydistribution_plot().
It reads wide sequences, event logs (with action), networks built from
sequences, clusterings, mixture fits and tna models; periods gives one
row per actor with the time axis split into days, weeks or another
period. An mcml from build_mcml() gets a multichannel figure instead:
a macro Summary panel and one panel per cluster (see the section
Multichannel view of an mcml). That figure is drawn with ggplot2 and
takes only type, trim, state_colors, na_color, main,
time_label (or xlab) and the mcml options (normalize, na,
panel, expand, combine, rest, rest_label); any other argument
given with an mcml is ignored with a warning of class
nestimate_ignored_argument. Every other figure is drawn with base
graphics.
The plot describes the sequences; it does not model them. The row order
of a heatmap comes from sort and is a display choice, so blocks of
similar rows are a reason to cluster the sequences with
build_clusters(), not a clustering in themselves. trim changes only
what is drawn, never the data.
Usage
sequence_plot(
x,
type = c("heatmap", "index", "distribution"),
sort = c("lcs", "frequency", "start", "end", "hamming", "osa", "lv", "dl", "qgram",
"cosine", "jaccard", "jw"),
tree = NULL,
group = NULL,
periods = NULL,
period_unit = c("day", "week", "month"),
fill = c("stretch", "pad"),
actor = NULL,
action = NULL,
time = NULL,
order = NULL,
scale = c("proportion", "count"),
geom = c("area", "bar"),
na = TRUE,
normalize = FALSE,
trim = NULL,
panel = c("both", "summary", "channels"),
expand = NULL,
combine = NULL,
rest = c("clusters", "pooled", "none"),
rest_label = "Other states",
trim_clusterwise = FALSE,
row_gap = 0,
dendrogram_width = 1.2,
k = NULL,
k_color = "white",
k_line_width = 2.5,
state_colors = NULL,
na_color = "grey90",
cell_border = NA,
frame = FALSE,
width = NULL,
height = NULL,
main = NULL,
show_n = TRUE,
time_label = "Time",
xlab = NULL,
y_label = NULL,
ylab = NULL,
tick = NULL,
ncol = NULL,
nrow = NULL,
combined = TRUE,
legend = NULL,
legend_size = NULL,
legend_title = NULL,
legend_ncol = NULL,
legend_border = NA,
legend_bty = "n",
cols = NULL
)
## S3 method for class 'mcml_sequence_plot'
print(x, ...)
Arguments
x |
The sequences to draw:
For the |
type |
The view: |
sort |
How rows are ordered, in the heatmap and within each panel of
the index view. |
tree |
A |
group |
The groups to draw in separate panels, one value per
sequence ( |
periods |
The column that splits each actor's sequence into periods
(days, weeks, ...): a column of the event log, or of the network's
metadata. |
period_unit |
With a date |
fill |
With |
actor, action, time, order |
For an event log: column names, as in
|
scale, geom, na |
For the distribution view, passed to
|
normalize |
For an |
trim |
A cut of the time axis (one number) or of the time axis and
the rows (two numbers), to stop a few long sequences from stretching
the plot and a few near-empty ones from padding it. It applies to all
three views, the The first number cuts the time axis. A fraction in (0, 1) judges each
time point on its own activity and keeps the busiest ones that together
hold that share of the observed states, ties going to the earlier one;
the rest are removed wherever they sit and the kept ones close up under
their own labels. So The second number ends each row earlier and never removes a row,
counted over the time points kept by the first: a value |
panel |
For an |
expand |
For an |
combine |
For an |
rest |
For an |
rest_label |
For an |
trim_clusterwise |
For a grouped index or distribution view with a
fractional |
row_gap |
The vertical gap between rows of the index view, as a
fraction of the row height, in [0, 1). Default |
dendrogram_width |
The width of the heatmap's dendrogram panel,
against a carpet width of 4: the default |
k |
For the heatmap: the number of clusters to cut the dendrogram
into, a single number of at least 2 and less than the number of rows;
thin horizontal lines then separate them in the carpet. Ignored
without a dendrogram (e.g. |
k_color |
The colour of the cluster separator lines. Default
|
k_line_width |
The line width of the cluster separators. Default
|
state_colors |
Colours for the fill keys, in one of two forms:
unnamed, one colour per state in level order (states are ordered as
For an |
na_color |
The colour of missing cells. Default |
cell_border |
The colour of each cell's border. Default |
frame |
Whether to draw a box around each panel; axis ticks and
labels appear either way. Default |
width, height |
Device dimensions in inches. In an interactive
session, giving either opens a new graphics device with
|
main |
The plot title. Default |
show_n |
Whether to append |
time_label, xlab |
The x-axis label; |
y_label, ylab |
The y-axis label of the distribution view; |
tick |
Label every |
ncol, nrow |
The panel grid of the grouped index and distribution
views. Default |
combined |
For the grouped index and distribution views: |
legend |
The legend position: |
legend_size |
The legend text size. Default |
legend_title |
The legend title. Default |
legend_ncol |
The number of legend columns. Default |
legend_border |
The colour of the legend swatches' borders. Default
|
legend_bty |
The legend box: |
cols |
For a wide data frame: the columns holding the positions.
Needed when they are not a numbered run ( |
... |
For the |
Value
For an mcml: the multichannel figure, one panel per channel
(the macro Summary and one per cluster), stacked, each with its own
legend of its clusters or states. When more than one channel is drawn
it is an mcml_sequence_plot, a gtable that its print() method
draws on a new page; when panel = "summary" leaves a single channel it
is a ggplot. The print() method returns its input invisibly.
Every other input is drawn with base graphics, and the call returns, invisibly, a list describing the figure, whose fields depend on the view:
- heatmap
ord(the row order plotted, as integer indices),codes(the integer-coded, trimmed sequence matrix),palette,levels(the state labels, parallel topalette) andsort_used(the ordering applied;"net_clustering"when a clustering's dendrogram was used).- index
codes,palette,levels,orders(a list of row orders, one per panel, indexing the original rows) andgroups(the panel labels).- with
periods ord(the row order of the actors),codes(an integer matrix, one row per actor and one column per period slot in thefill = "pad"layout, named"<period>.<slot>"),palette,levels,periods(the period labels in plotted order, aftertrim) andfill; withgroup, alsogroups(the panel labels) andorders(one row order per panel, indexing the actors),ordbeing their concatenation.- distribution
What
distribution_plot()returns:counts,proportions,levels,paletteandgroups.
Multichannel view of an mcml
An mcml built from sequences stores, for every cluster, the full
sequence matrix with the other clusters' states blanked out. Each cluster
is therefore a channel, and sequence_plot() stacks them:
SummaryThe macro sequence: at every time point, the cluster each subject is in.
- One panel per cluster
That cluster's own states, plus the time its subjects spend in the other clusters.
The options apply in this order, so each one sees the result of the one before:
-
combinemerges clusters into one channel. The merged group is then one cluster throughout the figure: one panel with all its states, one Summary key, one band in the other panels. The object itself is not changed. -
expandopens clusters (including a merged group, by its label) into their member states in the Summary panel only. -
restandrest_labelset how a cluster's panel shows the other clusters: one faded band per cluster labelled"<cluster> (<rest_label>)"(rest = "clusters"), one grey band labelledrest_label("pooled"), or nothing ("none"). -
na(distribution only) keeps theNAband of sequences that have ended (TRUE, shares of all subjects) or drops it (FALSE, shares of the subjects still running, so every panel stacks to 100 percent unlessrest = "none").normalize = TRUEinstead rescales each cluster panel to its own states, which ignoresrestandna.
panel draws the Summary or the cluster panels alone, and
trim cuts the time axis for every panel at once.
Methods
-
print.mcml_sequence_plot()draws the figuresequence_plot()returns for anmcmlwith more than one channel (the macroSummaryand one panel per cluster, each with its own legend) on a new page of the current graphics device.
See Also
distribution_plot, build_clusters,
build_mcml
Examples
sequence_plot(trajectories)
sequence_plot(trajectories, type = "index")
sequence_plot(trajectories, type = "distribution")
# One row per student, one block per day; each day's actions fill it.
daily <- data.frame(
student = rep(c("s1", "s2", "s3"), times = c(5, 9, 6)),
day = c("d1", "d2", "d2", "d3", "d3",
"d1", "d1", "d2", "d2", "d2", "d3", "d3", "d3", "d3",
"d1", "d1", "d1", "d2", "d3", "d3"),
action = c("plan", "read", "write", "read", "plan",
"read", "read", "plan", "write", "write", "read", "plan",
"write", "read", "plan", "plan", "write", "read", "write",
"read"))
sequence_plot(daily, actor = "student", action = "action", periods = "day")
sequence_plot(daily, actor = "student", action = "action", periods = "day",
fill = "pad", type = "index")
# The same from a network built with the period as its session.
daily_net <- build_network(daily, method = "relative", actor = "student",
action = "action", session = "day")
sequence_plot(daily_net, periods = "day")
# Multichannel MCML view: one channel per cluster + a macro Summary.
fit <- build_mcml(
group_regulation_long,
clusters = list(Cognitive = c("discuss", "synthesis", "consensus", "cohesion"),
Regulation = c("plan", "monitor", "adapt", "coregulate"),
Affective = "emotion"),
actor = "Actor", action = "Action", time = "Time")
sequence_plot(fit) # multichannel carpet
# Shape the multichannel view (see the section above).
sequence_plot(fit, type = "distribution",
combine = list(Task = c("Cognitive", "Regulation")),
expand = "Task") # merge, then open
# Colour by name: one state, one cluster, one combined group. Everything
# not named keeps its default colour.
sequence_plot(fit, type = "distribution",
combine = list(Task = c("Cognitive", "Regulation")),
state_colors = c(Task = "#0072B2", Affective = "#D55E00",
emotion = "#CC79A7"))
Identify the session behind each sequence
Description
session_ids() names every sequence of a network, or of a clustering
fitted on one, by the actor and session values it was built from, and
returns one row per sequence. A network built from long data with
actor and session holds one sequence per actor-session; its rows
are ordered by the grouping, not by the input, and a fitted clustering
reports its assignments in that same order. session_ids() returns the
key that joins them back to the input data, so no label has to be
parsed. For a clustering it adds each sequence's cluster, and for a
mixed Markov model also the posterior probability of that cluster.
Usage
session_ids(x, ...)
## Default S3 method:
session_ids(x, ...)
## S3 method for class 'netobject'
session_ids(x, ...)
## S3 method for class 'net_mmm'
session_ids(x, ...)
## S3 method for class 'net_clustering'
session_ids(x, ...)
Arguments
x |
A |
... |
Not used. |
Value
A data frame with one row per sequence, in the row order of the network's sequence data (and of the fit's assignments):
- sequence
The integer row number of the sequence.
- actor and session columns
The
actorandsessioncolumns given tobuild_network(), under their own names and with their own values.- session_label
The readable label of the sequence. With
time, the sessions split at time gaps carry an" s<n>"suffix, so this column tells them apart.- cluster
For a
net_mmmornet_clustering: the assigned cluster (integer).- posterior
For a
net_mmm: the posterior probability of the assigned cluster.
Errors
Raises an error of class nestimate_no_session_ids when x carries no
per-sequence metadata (a network built from wide data, a fit on wide
data or on a tna model, or a fit made before Nestimate 0.9.6, which
must be refitted) and when x is of another class, such as a
netobject_group. Raises an error of class
nestimate_session_ids_misaligned when the metadata and the sequences
differ in number.
See Also
build_network, build_mmm,
build_clusters
Examples
events <- data.frame(
student = rep(c("s1", "s2", "s3"), each = 8),
step = rep(c("a", "b"), each = 4, times = 3),
action = sample(c("read", "write", "test"), 24, replace = TRUE)
)
net <- build_network(events, actor = "student", session = "step",
action = "action", method = "relative")
session_ids(net)
fit <- build_mmm(net, k = 2, n_starts = 2, seed = 1)
session_ids(fit)
Set the state colours of a network object
Description
set_state_colors() attaches a palette to a network object, so every
figure drawn from it uses the same colours. state_colors(x) <- value is
the replacement form, and state_colors() reads back the colours in use.
One rule holds for colours across the package:
With no colours set, the states are drawn in the Okabe-Ito colours, dealt in the alphabetical order of the states, so a state has the same colour in every figure whatever the order of the network's nodes.
A palette set here replaces those colours for the states it names.
Objects computed from the network carry its colours: groups and their members,
build_clusters(),build_mmm()and the networksbuild_network()andcluster_network()build from them,bootstrap_network(),certainty(),permutation(),bayes_compare(),net_edge_betweenness(),entropy_network(),net_prune(),stability_landscape(),landscape_trend()andlandscape_surface(). A cluster or group that lacks a state keeps the colours of the others.Every figure that colours states follows them:
sequence_plot(),distribution_plot(),plot_state_frequencies(), theplot()methods ofstability_landscape()andlandscape_trend(), andcograph::splot()(through the network'smeta$splotcontract).-
state_colors =on one of those figures changes that figure only.
Usage
set_state_colors(x, colors)
## Default S3 method:
set_state_colors(x, colors)
## S3 method for class 'netobject'
set_state_colors(x, colors)
## S3 method for class 'htna'
set_state_colors(x, colors)
## S3 method for class 'mcml'
set_state_colors(x, colors)
## S3 method for class 'netobject_group'
set_state_colors(x, colors)
state_colors(x) <- value
Arguments
x |
A |
colors |
The palette: a named character vector of colours, such as
|
value |
The palette, as for |
Value
x with the palette stored on it; the class is unchanged.
state_colors() shows the colours it resolves to. For a netobject or
htna, the palette is also written, in node order, into the
meta$splot producer contract (defaults$node_fill), so
cograph::splot() draws the same colours without being passed any. A
netobject_group stores the palette on the group and on each member
network, so a member drawn on its own carries it too.
See Also
state_colors to read the resolved palette back.
Examples
net <- build_network(group_regulation_long, method = "relative",
actor = "Actor", action = "Action", time = "Time")
net <- set_state_colors(net, c(plan = "#0072B2", monitor = "#D55E00"))
state_colors(net)
Count the simplices that contain each node
Description
simplicial_degree() counts, for each node of a simplicial complex, how
many simplices of each dimension contain it: edges (dimension 1),
triangles (dimension 2) and so on. It is the higher-order counterpart of
a node's degree, and says which nodes take part in many group-level
structures rather than only in pairs.
The counts describe the complex as built, so they move with the
threshold or pathways build_simplicial() was given. A node in a clique
of m nodes is in choose(m - 1, k) of its k-simplices, so one large
clique raises the node's counts in every dimension up to the clique's
own;
compare nodes within a dimension.
Usage
simplicial_degree(sc, normalized = FALSE)
Arguments
sc |
A |
normalized |
Whether to divide each count of dimension k by the
largest possible one, |
Value
A data frame with one row per node, sorted by decreasing total:
node, then d0, d1, ... up to the dimension of the complex (the
number of simplices of that dimension containing the node; d0 is
always 1), and total, the sum of d1 onwards.
Examples
mat <- matrix(c(0,.6,.5,.6,0,.4,.5,.4,0), 3, 3)
colnames(mat) <- rownames(mat) <- c("A","B","C")
sc <- build_simplicial(mat, threshold = 0.3)
simplicial_degree(sc)
Tabulate the topological features of one or many networks
Description
simplicial_features() builds a simplicial complex for each network with
build_simplicial() and returns its topological summaries as a tidy data
frame, one row per network and one column per feature, ready to use as
regression predictors or to join onto unit-level outcomes. It takes one
network, a group of networks, the within-cluster networks of an mcml,
or a list of networks, at one threshold or a sweep of them.
Higher-order structure is reported as d2, d3, ...: the number of
simplices of that dimension. A 2-simplex is a triangle of three mutually
connected states, a 3-simplex a tetrahedron of four. These count
co-participation in a dense region, not statistical interaction. The
counts are a step function of threshold, so one threshold is a choice,
not a result: sweep several and check that a conclusion holds across
them.
Usage
simplicial_features(
x,
threshold = 0,
max_dim = 4L,
normalize = FALSE,
type = "clique"
)
Arguments
x |
The networks: a |
threshold |
The smallest absolute edge weight that makes an edge,
passed to |
max_dim |
The highest simplex dimension built, a whole number of at
least 1 (a fractional value is truncated). Default |
normalize |
Whether to divide the simplex counts ( |
type |
The complex construction passed to |
Value
A data frame with one row per network and threshold, ordered by
network name and then threshold, and columns network, threshold,
n_nodes, n_edges, b0 and b1 (the Betti numbers: connected
components and independent cycles, 0 when the complex has no such
dimension), euler (the Euler characteristic of the complex as
built), max_q (the top q-level of q_analysis(), the dimension of the
largest maximal simplex), d1, d2, ... up to dimension max_dim
(simplex counts by dimension) and higher_order (the total from d2 upward).
See Also
build_simplicial, betti_numbers,
q_analysis, outcome_model
Examples
m1 <- matrix(c(0, .6, .5, .6, 0, .4, .5, .4, 0), 3, 3,
dimnames = list(c("A", "B", "C"), c("A", "B", "C")))
m2 <- matrix(c(0, .2, 0, .2, 0, .1, 0, .1, 0), 3, 3,
dimnames = list(c("A", "B", "C"), c("A", "B", "C")))
simplicial_features(list(dense = m1, sparse = m2), threshold = 0.3)
# Sweep the threshold rather than committing to one.
simplicial_features(list(dense = m1), threshold = c(0.1, 0.3, 0.5))
Simulated counts of self-regulated learning strategies
Description
srl_strategies is a simulated dataset of how often 250 university
students used nine self-regulated learning (SRL) strategies, one row per
student and one count column per strategy. The strategies form three
clusters:
metacognitive (Planning, Monitoring, Evaluating), cognitive (Elaboration,
Organization, Rehearsal) and resource management (Help_Seeking,
Time_Mgmt, Effort_Reg). Strategies of the same cluster were simulated to
correlate moderately and those of different clusters more weakly; in the
bundled sample the correlations range from 0.18 to 0.49 within clusters
and from -0.13 to 0.31 across them.
Usage
srl_strategies
Format
A data frame with 250 rows and 9 columns, one row per student and one column per strategy. Every column is numeric (double) and holds a whole-number count of how often that student used the strategy; the observed values range from 0 to 37, with no missing values.
Examples
net <- build_network(srl_strategies, method = "glasso",
params = list(gamma = 0.5))
net
Estimate the stability landscape of a transition network
Description
stability_landscape() estimates the ball-in-cup landscape (Scheffer et
al. 2009) of a transition network, which plot() draws: one cup per
state, whose depth is the stability of that state, how long the process
stays once it is there. A
state with stay probability P_{ii} is left after
1 / (1 - P_{ii}) steps on average (its expected stay, or dwell
time), and its cup depth is the log of that time, -\log(1 - P_{ii}),
so that dwell time = e^{depth}: the escape-time law of a particle in
a potential well (Kramers 1940). A state that is left at once has depth 0,
no cup at all. It takes a "relative" or "frequency" network, a grouped
network (one landscape per group, on one state order) or the wide
sequences themselves, and gives every depth a percentile interval from
resampling whole sequences.
Depth is a property of the state alone. How often the process enters the
state is its share of the observed time steps, reported beside the
depth, and where it goes next is in the exit probabilities
(summary(x, table = "exits")), the one-step transition probabilities
P_{ij}: their denominator includes the stays, so a state's exits
sum to 1 - P_{ii}. The plot writes them under each cup. With three
states the result also reports the net circulation,
the net probability flux \pi_i P_{ij} - \pi_j P_{ji} around the
cycle, which stationarity makes equal on all three edges (Schnakenberg
1976): zero for a chain whose every transition is as common as its
reverse. The depths pool every sequence and every time step; whether they
change over time or along a covariate is what landscape_trend()
shows, and how long the process takes to get from one state to another is
given by passage_time().
Usage
stability_landscape(
x,
states = NULL,
iter = 1000L,
ci_level = 0.95,
seed = NULL,
cols = NULL
)
## S3 method for class 'net_landscape'
summary(object, table = c("cups", "exits", "circulation"), ...)
## S3 method for class 'net_landscape'
print(x, digits = 2, ...)
## S3 method for class 'net_landscape'
plot(x, state_colors = NULL, ...)
Arguments
x |
The network or sequences: a transition network from
|
states |
Every state, each named once, in the order to draw them (for
example from least to most engaged). Default |
iter |
The number of bootstrap resamples of sequences behind the
intervals, a non-negative whole number. Default |
ci_level |
The interval level, a number between 0 and 1. Default
|
seed |
A seed for the resampling. It applies to this call only: the
session's random state is restored afterwards. Default |
cols |
For a wide data frame: the columns holding the positions.
Needed when they are not a numbered run ( |
object |
For the |
table |
For the |
... |
Ignored. |
digits |
For the |
state_colors |
For the |
Details
Network input replays the network's per-sequence weighting, concatenation
and boundary markers (a start or end state is a state of the
landscape), and the concatenated sequences are the resampling units. An
end state, or any state seen only at the last position of a sequence, has
no outgoing transitions, so its depth, stay and dwell are NA, and the
plot draws it flat at depth 0, without a cup.
Scaled, thresholded or otherwise modified networks whose weights do not
match their stored sequences are refused; pass the original sequences to
estimate a new landscape. The share column counts prepared positions
without sequence weighting.
In a resample where a state is never left, its depth is infinite, so an
upper interval limit can be Inf; a resample in which a state never
occurs is left out of that state's interval (resamples counts the
rest). Only the cup floors carry data in the plot; the curve between them
is a smooth join, and every rim is drawn at 0.
Value
A net_landscape object. print() shows each state's depth with
its interval, expected stay, stay probability and share, and the net
circulation for three states; summary() returns the tables below;
plot() returns the landscape as a ggplot, one panel per network, with
the intervals as bars and the expected stay, share and exit
probabilities written under each cup, and with three states the net
circulation and its interval at the top of the panel. print() returns its input
invisibly.
summary() returns a data frame. With table = "cups": one row per
network and state, with group, state, depth, ci_lower,
ci_upper, dwell (expected consecutive steps in the state), stay
(P_{ii}), share (share of observed time steps in the state),
n_from (transitions out of the state, self-transitions included) and
resamples. With table = "exits": one row per network and pair of
distinct states, with group, from, to, probability (the one-step transition
probability P_{ij}, stays included in the denominator) and count.
With table = "circulation": one row per network, with group,
cycle (the direction of the net flow), current, ci_lower,
ci_upper and resamples (resamples with a unique stationary
distribution).
The object's fields:
- fits
One fit per network, named
"network"for a single one and by group for a grouped one; each holds the cups, exits and circulation tables and the numbers of sequences and transitions.- states
The states, in drawing order.
- iter, ci_level
The resampling settings.
Errors
nestimate_latency_resampling for a latency network (or a group holding
one);
nestimate_single_sequence for a network or data resting on one sequence
when iter > 0, whose intervals would have zero width;
nestimate_not_markov for a network that is not a transition network;
nestimate_bad_input for states that do not name every state once,
fewer than two states, input without sequences (a network built from an
edge list included), an mcml layer combined by other than a sum, or a
network whose weights cannot be rebuilt from its sequences;
nestimate_landscape_unestimable for a state that is never left or input
with no observed transition.
References
Kramers, H. A. (1940). Brownian motion in a field of force and the diffusion model of chemical reactions. Physica, 7, 284–304.
Scheffer, M., Bascompte, J., Brock, W. A., et al. (2009). Early-warning signals for critical transitions. Nature, 461, 53–59.
Schnakenberg, J. (1976). Network theory of microscopic and macroscopic behavior of master equation systems. Reviews of Modern Physics, 48, 571–585.
See Also
landscape_surface, passage_time,
markov_stability
Examples
net <- build_network(trajectories, method = "relative")
land <- stability_landscape(net,
states = c("Disengaged", "Average", "Active"), iter = 20, seed = 1)
land
summary(land, table = "exits")
plot(land)
Get the state colours of an object
Description
state_colors() returns the palette an object draws with: the colours set
with set_state_colors() plus the defaults filled in for every other
state, so the table shows what the figures use.
Usage
state_colors(x, ...)
## Default S3 method:
state_colors(x, ...)
## S3 method for class 'netobject'
state_colors(x, ...)
## S3 method for class 'htna'
state_colors(x, ...)
## S3 method for class 'mcml'
state_colors(x, ...)
## S3 method for class 'netobject_group'
state_colors(x, ...)
Arguments
x |
A |
... |
Not used. |
Value
A data frame with one row per colour key the object carries
(for a netobject_group, the states of all its networks): state (the
key), color (the colour it draws with) and source ("set" when the
palette named it, "default" when it fell back to Okabe-Ito). For an
mcml, the cluster names follow the states.
See Also
Examples
net <- build_network(group_regulation_long, method = "relative",
actor = "Actor", action = "Action", time = "Time")
state_colors(set_state_colors(net, c(plan = "#0072B2")))
Tabulate the state distribution of each group
Description
state_distribution() counts how often each state occurs in the
sequences behind a network and returns one row per group and state,
with the count and the share within the group. The groups follow the
class: a single netobject is one group, "all", unless it carries node
groups, which then form the groups (states in none are "(ungrouped)");
an htna network has one group per actor; a netobject_group one per
network, named as in the group (or "Group 1", "Group 2", ...); an
mcml one per cluster, with the node labels it was given in place of
the raw codes. Missing and empty cells are not counted.
This is the table that plot_state_frequencies() draws. To count the states of raw sequence data, use state_frequencies() instead.
Usage
state_distribution(x, ...)
## S3 method for class 'netobject'
state_distribution(x, ...)
## S3 method for class 'htna'
state_distribution(x, ...)
## S3 method for class 'mcml'
state_distribution(x, include_macro = FALSE, ...)
## S3 method for class 'netobject_group'
state_distribution(x, ...)
## S3 method for class 'state_freq'
state_distribution(x, ...)
## Default S3 method:
state_distribution(x, ...)
Arguments
x |
A |
... |
Not used. The |
include_macro |
For an |
Value
A data frame with one row per group and state and the columns
group (character), state (character), count (integer) and
proportion (the state's share of its group's events). Within a group
the rows run from the most to the least frequent state; the "macro"
group is in alphabetical order.
Examples
data(group_regulation_long, package = "Nestimate")
net <- build_network(group_regulation_long, method = "frequency",
format = "long", actor = "Actor", action = "Action",
order = "Time", group = "Course")
state_distribution(net)
Count state frequencies in trajectories
Description
state_frequencies() counts how often each state occurs across all
trajectories, and returns one row per state, most frequent first.
Missing values are not counted.
Usage
state_frequencies(data)
Arguments
data |
The trajectories: a list of state vectors, a data frame or
character matrix with one row per trajectory and one column per time
point, a |
Value
A data frame with one row per distinct state, sorted by count
(descending), with columns state, count and proportion (the
state's share of all observed states, rounded to 4 decimal places).
Examples
trajs <- list(c("A","B","C"), c("A","B","A"))
state_frequencies(trajs)
Subtract one network from another
Description
subtract_networks() subtracts one network's weights from another's,
cell by cell, and returns the difference x - y as a netdifference
object: a network whose edge weights are the signed differences. It takes
any pair of networks on the same nodes (netobjects, cograph_networks
or square numeric matrices); for an edge-betweenness difference, subtract
two net_edge_betweenness results. cograph::splot(d) or
cograph::plot_difference(d) draws the signed difference network, with
cograph's colouring and node palette.
The difference is taken between two point estimates and carries no
uncertainty, so a large difference on a rarely observed edge can be
noise. To see which edges differ beyond sampling variation, compare the
two networks with permutation() or bayes_compare();
as_netdifference() turns a bayes_compare() result into the same kind
of object, keeping, by default, only the credible differences.
Usage
subtract_networks(x, y)
## S3 method for class 'netdifference'
print(x, max_print = 12L, ...)
Arguments
x, y |
The two networks: |
max_print |
For the |
... |
For the |
Value
A netdifference object, which is also a netobject (method
"difference"). print() lists the edges present in either network,
largest absolute difference first, with both weights and their
difference (for an undirected difference, each pair once);
cograph::splot() draws it. Beside the usual netobject fields, its
weights and difference_matrix both hold x - y, and x and y
hold the two weight matrices that were subtracted.
The print() method returns its input invisibly.
Examples
early <- data.frame(
V1 = c("A","B","A","C"), V2 = c("B","C","B","A"),
V3 = c("C","A","C","B"))
late <- data.frame(
V1 = c("B","A","C","B"), V2 = c("C","B","A","C"),
V3 = c("A","C","B","A"))
a <- build_network(early, method = "relative")
b <- build_network(late, method = "relative")
subtract_networks(a, b)
# edge-betweenness difference:
subtract_networks(net_edge_betweenness(a), net_edge_betweenness(b))
Student engagement trajectories
Description
trajectories is a dataset of the engagement states ("Active",
"Average" and "Disengaged") of 138 students over the 15 successive
courses of a programme. It is in wide format, one row per student and one
column per course. A missing value
occurs only as a run at the end of a row, which marks drop-out; two rows
are missing throughout.
Usage
trajectories
Format
A character matrix with 138 rows and 15 columns named "1" to
"15", the courses in the order they were taken. Each entry is "Active", "Average",
"Disengaged" or NA. The trailing NA runs are what the
right-censored sequence verbs (actor_endpoints(),
mark_terminal_state()) are built to read.
Examples
sequence_plot(trajectories, main = "Engagement trajectories")
sequence_plot(trajectories, k = 3)
sequence_plot(trajectories, type = "distribution")
Compute the transition entropy of a Markov chain
Description
transition_entropy() measures how uncertain a Markov chain's next step
is, at three levels: the branching entropy of each state (how evenly its
outgoing transitions spread), the entropy of the stationary distribution,
and the chain's entropy rate, the average uncertainty per step. It takes a
transition network, a tna model, a transition matrix or wide sequence
data; a netobject_group gives one result per group. The entropy rate
h(P) = -\sum_i \pi_i \sum_j P_{ij} \log_b P_{ij},
with \pi the stationary distribution, is the per-step uncertainty of
the chain's trajectories (Cover & Thomas, 2006, ch. 4). It was introduced
to behavioural research as gaze transition entropy by Krejtz et al. (2015)
and tracked in real time as mobile transition matrix entropy by Krejtz et
al. (2025). The normalised values divide by \log_b n, the entropy of
uniform branching among n states; they are the scale-free variants
those papers report.
An entropy rate near 0 means the current state almost fixes the next one;
near the ceiling \log_b n (normalised 1), every next state is about
equally likely. The redundancy H(\pi) - h(P) is the uncertainty that
knowing the current state removes, zero when successive states are
independent. All of these are point estimates from one transition matrix:
entropy_bayes() gives their credible intervals, entropy_network()
shows which transitions carry the entropy, and entropy_trajectory() how
it changes over time. A chain with more than one closed class has more
than one stationary distribution; check its classes with
chain_structure().
Usage
transition_entropy(x, base = 2, normalize = TRUE)
## S3 method for class 'net_transition_entropy'
print(x, digits = 3, ...)
## S3 method for class 'net_transition_entropy_group'
print(x, ...)
## S3 method for class 'net_transition_entropy_group'
summary(object, table = c("states", "chain"), ...)
## S3 method for class 'net_transition_entropy_group'
plot(x, title = "Transition Entropy", fill = "#0072B2", ...)
## S3 method for class 'net_transition_entropy'
summary(object, table = c("states", "chain"), ...)
## S3 method for class 'net_transition_entropy'
plot(x, title = "Transition Entropy", fill = "#0072B2", ...)
Arguments
x |
The chain: a |
base |
The logarithm base, which sets the unit: |
normalize |
Whether rows that do not sum to 1 (a frequency network, a
count matrix) are divided by their sums, with a warning. With |
digits |
For the |
... |
For the |
object |
For |
table |
For |
title |
For |
fill |
For |
Details
The convention 0 \log 0 = 0 applies, so an absorbing or
deterministic row has zero branching entropy. The chain need not be
irreducible: \pi is the eigenvector of P^\top for the
eigenvalue closest to 1, as elsewhere in the package. For a chain with
more than one closed class this is one stationary distribution among
many; when some of
its probabilities are zero, a warning says so, and they are set to machine
epsilon and the distribution renormalised before the entropies are
computed.
h(P) \le H(\pi) holds, with equality if and only if successive
states are independent. The deficit H(\pi) - h(P) is reported as
redundancy, a measure of how much memory the chain has at order 1.
Value
A net_transition_entropy object, or for a netobject_group a
net_transition_entropy_group: a named list of them, one per group.
print() shows the entropy rate, stationary entropy and redundancy, raw
and normalised, and for a group the entropy rate of each group.
summary() returns a data frame. With table = "states" (default),
one row per state (state, the stationary probability, raw and
normalised branching entropy, the state's additive contribution
\pi_i H(P_{i\cdot}) to the entropy rate and that contribution as
a percentage of it), sorted by contribution, largest first; for a group,
with a group column first. With table = "chain", one row per
chain-level quantity (entropy rate, stationary entropy, redundancy and
the ceiling, raw and normalised, with the unit); for a group, one row
per group (group, n_states, the raw and normalised entropy rate and
stationary entropy, redundancy and unit). For a group, plot()
draws the bar chart below in one panel per group.
plot() returns a ggplot bar chart of each state's branching entropy,
with bar widths proportional to the stationary probability (so a bar's
area is proportional to the state's contribution), a dashed line at the
entropy rate h(P) and a dotted line at the ceiling \log_b n
(uniform branching). The print() methods return their input
invisibly. The object's fields:
- row_entropy
Named numeric vector, one value per state: its branching entropy
H(P_{i\cdot}) = -\sum_j P_{ij} \log_b P_{ij}.- row_entropy_norm
row_entropydivided by the ceiling\log_b n, in[0, 1]; all zeros whenn = 1.- stationary
Named numeric vector: the stationary distribution
\pi.- stationary_entropy
H(\pi) = -\sum_i \pi_i \log_b \pi_i, the entropy of\piread as an independent draw each step; an upper bound on the entropy rate.- stationary_entropy_norm
stationary_entropydivided by the ceiling\log_b n.- entropy_rate
h(P) = \sum_i \pi_i H(P_{i\cdot}), the Shannon-McMillan-Breiman entropy rate.- entropy_rate_norm
entropy_ratedivided by the ceiling\log_b n.- redundancy
H(\pi) - h(P), the entropy deficit due to serial dependence; zero for an independent chain (every row ofPequal to\pi).- redundancy_norm
The relative redundancy
(H(\pi) - h(P)) / H(\pi), the share of the stationary entropy that order-1 memory removes; notredundancydivided by\log_b n.0whenH(\pi) = 0.- max_entropy
The normalising ceiling
\log_b n.- base
The logarithm base used.
- states
Character vector of state names.
References
Cover, T.M. & Thomas, J.A. (2006). Elements of Information Theory, 2nd ed., chapter 4. Wiley.
Krejtz, K., Duchowski, A., Szmidt, T., Krejtz, I., Gonzalez Perilli, F., Pires, A., Vilaro, A., & Villalobos, N. (2015). Gaze transition entropy. ACM Transactions on Applied Perception, 13(1), 4:1-4:20. doi:10.1145/2834121
Krejtz, K., Hughes, C.J., Stasiak, I., Duchowski, A., & Krejtz, I. (2025). Real-time mobile transition matrix entropy based on eye and head movements. Proceedings of ETRA '25. doi:10.1145/3715669.3723128
Shannon, C.E. (1948). A mathematical theory of communication. Bell System Technical Journal, 27, 379-423.
See Also
entropy_network for the edge-level decomposition,
entropy_trajectory for the sliding-window version,
entropy_bayes for credible intervals;
markov_stability, passage_time,
markov_order_test, chain_structure
Examples
net <- build_network(as.data.frame(trajectories), method = "relative")
te <- transition_entropy(net)
print(te)
summary(te)
plot(te)
Validate the structure of a network object
Description
validate_netobject() checks that an object meets the structure Nestimate
netobjects and psychnets objects share, so either can be passed
across the package boundary. It is the one place that says what a network
object is, so a change on either side (a renamed field, a mistyped edge
column) fails here instead of further down, for instance when the network
is drawn.
The checks are the shared part only: the object inherits
cograph_network; weights is a square numeric matrix with node names as
dimnames; nodes is a data frame with columns id, label and name,
one row per node; edges is a data frame with columns from, to and a
numeric weight, whose endpoints are integer node indices (Nestimate) or
node labels (psychnets); directed is a single logical value; and
method is a single string. The x/y layout columns of nodes and
Nestimate's own fields (data, level, ...) are not required.
Usage
validate_netobject(x)
Arguments
x |
The object to check, expected to be a |
Value
TRUE, invisibly, when x passes every check. Otherwise an error
that lists every check it failed.
See Also
Examples
net <- build_cor(data.frame(a = rnorm(50), b = rnorm(50), c = rnorm(50)))
validate_netobject(net)
Verify a simplicial complex against igraph
Description
verify_simplicial() builds the clique complex of mat with
build_simplicial() and checks it against two independent references:
its simplices
against the cliques igraph::cliques() finds in the same thresholded
graph, and its Euler characteristic against the alternating sum of its
Betti numbers (the Euler-Poincare theorem). Its print method shows the
result of each check and the Betti numbers; it is meant for testing. It needs
igraph, and raises an error without it.
Usage
verify_simplicial(mat, threshold = 0)
## S3 method for class 'net_simplicial_check'
print(x, ...)
Arguments
mat |
A square weight matrix, or a network object whose weight
matrix |
threshold |
The smallest absolute edge weight an edge needs to
enter, as in |
x |
For the print() method: a |
... |
For the print() method: not used. |
Details
The complex is built with the default max_dim = 10, while
igraph::cliques() has no size limit, so a graph with a clique of more
than 11 nodes reports a mismatch, with a warning of class
nestimate_truncated_complex from betti_numbers().
Value
A list of class net_simplicial_check: cliques_match (whether
the simplices equal the cliques from igraph::cliques() exactly),
n_simplices_ours, n_simplices_igraph, betti, euler,
euler_matches (whether euler equals the alternating sum of betti)
and f_vector. For the print() method: x, invisibly, after printing
the two checks and the Betti numbers.
Examples
mat <- matrix(c(0,.6,.5,.6,0,.4,.5,.4,0), 3, 3)
colnames(mat) <- rownames(mat) <- c("A","B","C")
verify_simplicial(mat, threshold = 0.3)
Bootstrap network-level statistics by resampling nodes
Description
vertex_bootstrap() resamples the nodes of one observed network and
returns bootstrap standard errors, bias and confidence intervals for
network-level statistics: density, mean weight, strength centralisation
and, for a directed network, reciprocity, plus any statistic of your own
(Snijders & Borgatti 1999). It needs only the weight matrix, so it works
on any netobject or cograph_network, including those that carry no
data, such as the constituents of build_mlvar() or the networks
as_tna() returns for an mcml object built from a weight matrix, and
on a plain square weight matrix.
The intervals describe how much a whole-network statistic depends on
which nodes happen to make up the network, with the edge weights taken
as given. They say nothing about how the weights themselves vary from
sample to sample; when the sequences or rows behind a network are
available, bootstrap_network() resamples those instead. Two networks
are compared on these statistics with vertex_compare().
Usage
vertex_bootstrap(
x,
iter = 1000L,
ci_level = 0.05,
ci_method = c("percentile", "basic"),
statistics = NULL,
statistic_fn = NULL,
directed = NULL,
seed = NULL
)
## S3 method for class 'net_vertex_bootstrap'
print(x, digits = 3, ...)
## S3 method for class 'net_vertex_bootstrap'
summary(object, ...)
## S3 method for class 'net_vertex_bootstrap'
plot(x, bins = 30, ...)
Arguments
x |
The network: a |
iter |
The number of bootstrap replicates, at least 2. Default
|
ci_level |
The significance level of the confidence intervals, not
their coverage: |
ci_method |
How the intervals are formed. |
statistics |
The built-in statistics to compute (see Details).
Default |
statistic_fn |
Statistics of your own, as a named list of functions,
each taking the weight matrix and returning a single number. They are
computed beside the built-ins on the whole matrix, diagonal included.
Each needs a name of its own: a name used twice or taken by a
built-in statistic raises an error of class |
directed |
Whether the network is directed, which decides how
collisions are filled and whether |
seed |
A seed passed to |
digits |
For the |
... |
Not used. |
object |
For the |
bins |
For the |
Details
Each replicate draws n node indices with replacement and sets
W_b[i, j] = W[idx_i, idx_j]. When the same original node is drawn for
two different positions, the off-diagonal cell between them would be a
self-pair; following Snijders & Borgatti, it is filled with the weight of
a randomly chosen pair of distinct original nodes. Diagonal cells keep the
original self-weight of the resampled node (W[idx_i, idx_i]), since
self-loops are meaningful in transition networks. For an undirected
network the substitution is made in the upper triangle and mirrored, so
every replicate stays symmetric.
The built-in statistics are computed on the off-diagonal cells:
densityThe share of non-zero off-diagonal cells.
mean_weightThe mean of the non-zero off-diagonal weights.
centralizationFreeman-type strength centralisation,
sum(max(s) - s) / ((n - 1) * max(s)), wheresis each node's total (in plus out) absolute strength without its self-loop: 0 when every node has the same strength, approaching 1 for a star.reciprocityDirected networks only. Weighted reciprocity,
sum(pmin(|W|, |t(W)|)) / sum(|W|)over the off-diagonal cells: the share of the total weight that is reciprocated.
A statistic is NA when it is undefined: mean_weight with no non-zero
cell, centralization when every strength is 0, reciprocity when the
total weight is 0. NA replicates are left out of the bootstrap mean,
standard deviation and quantiles.
Value
A net_vertex_bootstrap object. Printing it shows the number of
nodes, the directedness, the number of replicates and the interval
level and method, then the summary table; summary() returns that
table as a data frame with one row per statistic and the columns
statistic, observed, boot_mean, boot_sd, bias
(boot_mean - observed), ci_lower and ci_upper; plot() draws the
bootstrap distributions. The object holds:
- summary
The summary table described above.
- boot_stats
A matrix of the replicate values,
iterrows by one column per statistic.- observed
The observed statistics, as a named numeric vector.
- iter, ci_level, ci_method, directed, n_nodes
The settings used and the number of nodes.
The print() method returns its input invisibly, summary() the
summary data frame and plot() a ggplot object.
Methods
plot() draws a histogram of the replicate values for each statistic,
one panel per statistic with its own scales, a solid line at the observed
value and dashed lines at the interval bounds.
References
Snijders, T. A. B., & Borgatti, S. P. (1999). Non-parametric standard errors and tests for network statistics. Connections, 22(2), 161-170.
Davison, A. C., & Hinkley, D. V. (1997). Bootstrap Methods and their Application. Cambridge University Press.
See Also
bootstrap_network for case-resampling edge-weight
inference, centrality_stability for case-dropping
centrality stability.
Examples
seqs <- data.frame(
T1 = c("plan", "code", "debug", "plan", "test", "code"),
T2 = c("code", "debug", "code", "plan", "code", "test"),
T3 = c("debug", "code", "plan", "code", "debug", "plan"),
T4 = c("test", "plan", "test", "debug", "plan", "code")
)
net <- build_network(seqs, method = "relative")
vb <- vertex_bootstrap(net, iter = 20, seed = 1)
summary(vb)
plot(vb)
Test whether network-level statistics differ between two networks
Description
vertex_compare() tests whether two observed networks differ in their
network-level statistics, the two-network test Snijders & Borgatti
(1999) proposed the vertex bootstrap for. Each network's statistics get
vertex-bootstrap standard errors from vertex_bootstrap(), and each
difference is tested with
z = (\hat{\theta}_x - \hat{\theta}_y) /
\sqrt{SE_x^2 + SE_y^2}
against a standard normal distribution, with a normal-approximation confidence interval for the difference. It covers density, mean weight, centralisation, reciprocity and any statistic of your own.
The test is about whole-network descriptives, and its standard errors
reflect the resampling of nodes, not of the cases behind the weights.
The p-values are not adjusted for the number of statistics tested; pass
them to stats::p.adjust() when several are read together. When the raw
data of both networks are available, permutation() and nct() compare
them edge by edge.
Usage
vertex_compare(
x,
y,
iter = 1000L,
ci_level = 0.05,
statistics = NULL,
statistic_fn = NULL,
directed = NULL,
seed = NULL,
labels = c("x", "y")
)
## S3 method for class 'net_vertex_comparison'
print(x, digits = 3, ...)
## S3 method for class 'net_vertex_comparison'
summary(object, ...)
## S3 method for class 'net_vertex_comparison'
plot(x, ...)
Arguments
x, y |
The two networks: |
iter |
The number of bootstrap replicates, at least 2. Default
|
ci_level |
The significance level of the normal-approximation
intervals for the differences: |
statistics |
The built-in statistics to compare, as named for
|
statistic_fn |
Statistics of your own, as a named list of functions,
each taking the weight matrix and returning a single number. They are
computed beside the built-ins on the whole matrix, diagonal included.
Each needs a name of its own: a name used twice or taken by a
built-in statistic raises an error of class |
directed |
Whether the networks are directed, which decides how
collisions are filled and whether |
seed |
A seed passed to |
labels |
Two names for the networks, used in the print header and
the plot axis. The columns are always |
digits |
For the |
... |
Not used. |
object |
For the |
Value
A net_vertex_comparison object. Printing it shows the two
networks' sizes and the first network's number of replicates, then the
summary table
with significance stars; summary() returns that table as a data frame
with one row per statistic and the columns statistic, the two
observed values (observed_x, observed_y), diff (first minus second),
se_diff, z, p_value (two-sided), ci_lower and ci_upper;
plot() draws the differences with their intervals. When a statistic
has no bootstrap variation in either network (both standard errors 0),
its z and p_value are NA. The object holds:
- summary
The summary table described above.
- x, y
The two
net_vertex_bootstrapresults.- labels, ci_level
The settings used.
The print() method returns its input invisibly, summary() the
summary data frame and plot() a ggplot object.
Methods
plot() draws each statistic's difference as a point with its
normal-approximation interval, beside a dashed line at zero; intervals
that exclude zero are drawn in red, the others in blue.
References
Snijders, T. A. B., & Borgatti, S. P. (1999). Non-parametric standard errors and tests for network statistics. Connections, 22(2), 161-170.
See Also
vertex_bootstrap, nct for the
permutation-based comparison of edge-level structure when raw data
are available, permutation.
Examples
states <- c("plan", "code", "debug", "test")
s1 <- data.frame(
T1 = rep(states, 5), T2 = rep(rev(states), 5),
T3 = rep(states[c(2, 3, 4, 1)], 5)
)
s2 <- data.frame(
T1 = rep(states[c(3, 1, 4, 2)], 5), T2 = rep(states, 5),
T3 = rep(states[c(4, 3, 1, 2)], 5)
)
net1 <- build_network(s1, method = "relative")
net2 <- build_network(s2, method = "relative")
cmp <- vertex_compare(net1, net2, iter = 20, seed = 1)
summary(cmp)
Convert wide sequences to long format
Description
wide_to_long() turns sequences in wide format (one row per sequence,
one column per time point) into long format, with one row per sequence
and time point. The time point columns are those named time_prefix
followed by a number (V1, V2, ...); every other column is kept and
repeated on each row of its sequence.
Usage
wide_to_long(
data,
id_col = NULL,
time_prefix = "V",
action_col = "Action",
time_col = "Time",
drop_na = TRUE
)
Arguments
data |
A data frame in wide format, one row per sequence. |
id_col |
The column identifying each sequence. Default |
time_prefix |
The prefix of the time point columns: with |
action_col |
The name of the state column in the output. Default
|
time_col |
The name of the time column in the output. Default
|
drop_na |
Whether to drop the rows whose state is missing, such as
the padding after a shorter sequence ends. Default |
Details
The long format is the event-log layout read by build_network() with
action (and prepare()): give action = "Action", actor = "id" and
time = "Time" (or the names chosen here).
Value
A data frame in long format, one row per sequence and time point, sorted by identifier and then time. Its columns are the identifier, the other kept columns, the time and the state:
- id
The sequence identifier, named by
id_col; withid_col = NULLit is calledidand holds the row number of the wide input (integer).- Time
The time point within the sequence (integer), taken from the number in the wide column name; named by
time_col.- Action
The state at that time point; named by
action_col.
See Also
long_to_wide for the reverse conversion,
prepare_for_tna for preparing data for TNA analysis.
Examples
wide_data <- data.frame(
V1 = c("A", "B", "C"), V2 = c("B", "C", "A"), V3 = c("C", "A", "B")
)
long_data <- wide_to_long(wide_data)
head(long_data)
Build a window-based transition network from one-hot data
Description
wtna() builds a network from one-hot data, where each row is a time
point and each code column holds 1 when that code is active, by counting
codes across windows of consecutive rows. It returns a directed
transition network (codes active in one window, followed by codes active
in the next), an undirected co-occurrence network (codes active in the
same window), or both. With actor, each actor's rows are counted on
their own and the counts summed, so no window spans two actors. The
networks are the ones build_network(method = "wtna") and
build_network(method = "wtna_cooccurrence") estimate.
The weights count pairs of active codes, not events: a row with several
active codes adds to several edges at once, and a larger window pairs
more rows. Compare networks built with the same window_size and
mode. How far the weights move under resampling of actors is checked
with bootstrap_network(), and two networks are compared with
permutation(); both need actor, since rows without it form a single
unit.
Usage
wtna(
data,
method = c("transition", "cooccurrence", "both"),
type = c("frequency", "relative"),
codes = NULL,
window_size = 3L,
mode = c("non-overlapping", "overlapping"),
actor = NULL
)
## S3 method for class 'wtna_mixed'
print(x, ...)
Arguments
data |
A data frame or matrix whose rows are time points, in order,
holding the one-hot code columns and, optionally, the |
method |
The network to build: |
type |
The weights: |
codes |
The one-hot columns, as names, as column positions, or as a
single |
window_size |
The number of consecutive rows in a window, a whole
number of at least 1. Default |
mode |
How windows are formed when |
actor |
The column, or columns, naming who each row belongs to.
The counts are computed per actor (per combination of values, for
several columns) and summed. Default |
x |
For the |
... |
For the |
Details
Transitions: with window_size = 1, crossprod(X[-n, ], X[-1, ])
counts how often code i is active in row t and code j in row t + 1. With
larger windows, every row of a window is paired with every row of the
next window, which is the outer product of the two windows' column sums;
a final, shorter window is counted as the successor of the last full
one.
Co-occurrence: with window_size = 1, crossprod(X) counts the
codes active in the same row, so the diagonal is how often each code is
active. With larger windows, every row of a window is paired with every
row of the same window, itself included, which is the outer product of
the window's column sums.
Windows: in non-overlapping windows a code counts once for each row it is active in. These counts follow tna's windowed algorithm.
Per actor: with actor, the counts are computed per group and
summed.
Value
For method = "transition" or "cooccurrence": a netobject, as build_network() returns it, with method set to "wtna_transition" or "wtna_cooccurrence". print()
shows the weights and, for transitions, the initial probabilities;
-
extract_edges()gives one row per edge; -
extract_initial_probs()gives the initial-state distribution of a transition network; -
cograph::splot()draws it; -
bootstrap_network()resamples its actors, andpermutation()compares it with a second network by permuting actors.
It is directed
only for transitions, holds the input as given in data,
and records the windowing settings (type, window_size, mode,
codes, actor) in params. A transition network also stores the
initial-state distribution in initial: for each actor (the first
actor column when there are several), the codes active in its first
row with an active code share its weight equally, and the shares are
averaged over actors (without actor, the first row with an active
code in the whole data).
For method = "both": a wtna_mixed object, a list of the
transition and cooccurrence networks (each a netobject as above)
and method = "wtna_both". Its print() gives the node and edge
counts of each network and returns its input invisibly;
bootstrap_network() and permutation() test both networks.
See Also
Examples
oh <- matrix(c(1,0,0, 0,1,0, 0,0,1, 1,0,0), nrow = 4, byrow = TRUE,
dimnames = list(NULL, c("A","B","C")))
w <- wtna(oh)
# Simple one-hot data
df <- data.frame(
A = c(1, 0, 1, 0, 1),
B = c(0, 1, 0, 1, 0),
C = c(0, 0, 1, 0, 0)
)
# Transition network
net <- wtna(df)
print(net)
# Both networks
nets <- wtna(df, method = "both")
print(nets) # the transition and the co-occurrence network
# With windowing
net <- wtna(df, window_size = 2, mode = "non-overlapping")