Package {Nestimate}


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):

Author(s)

Maintainer: Mohammed Saqr saqr@saqr.me [copyright holder]

Authors:

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:


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 "Action"; a name that is not a column raises an error.

states

The states to make columns for, in that order. Default NULL, every non-missing value of the action column in order of first appearance. A listed state that never occurs gets a column of zeros, and a row whose state is not listed is 0 in every column.

drop_action

Whether to remove the action column. Default TRUE.

sort_states

Whether to sort the state columns alphabetically (in level order for a factor action column). Default FALSE.

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 NA for a missing observation. Without cols, every column is read as a position, so the frame must be one column or a numbered run of positions (T1, T2, ...); a frame with other columns beside them, such as an id, raises an error of class nestimate_bad_input. A table from mark_terminal_state() or mark_first_state() is read as it is, because those functions mark their columns as positions.

cols

The columns holding the positions, in order; the other columns are ignored. A name not in data raises an error of class nestimate_bad_input. Default NULL (every column).

Value

A data frame with one row per actor and the columns:

actor

The row name when data has row names other than 1, 2, ...; otherwise the row number.

first_state, last_state

The first and the last observed state.

first_step, last_step

The positions (column numbers among the position columns) of the first and the last observed state.

n_observed

The number of observed cells.

dropped_out

TRUE when last_step is 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 build_network() accepts (a sequence data frame, an event log, an edge list, a transition matrix, a netobject or a tna model); or an mcml object, which provides the cluster membership and, when it was built from a wide sequence frame or an event log, the data as well (see data); or a net_mmm fitted by cluster_mmm() on an HTNA network, which is materialised into one HTNA per sequence cluster using its preserved actor partition.

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 NULL, under which the node groups of the network (node_groups with node and group columns) or an mcml's clusters are used; with neither, an error is raised. Every node must belong to a cluster, and unassigned nodes are named in an error. A fitted net_mmm takes no clusters: passing them raises an error.

method

The estimator passed to build_network(). Default "relative" (row-normalised transitions).

...

Further arguments for build_network(), such as actor, action and time for an event log. A group argument raises an error, because a single network is expected.

data

For the mcml method: the original data the mcml was built from. Optional when it was built from a wide sequence frame, a character sequence matrix, or an event log (which build_mcml() turns into sequences first): that source is kept on the object, so as_htna(mcml) works on its own, except for an mcml built with labels, whose kept source holds the original state names (pass clusters with those names then). Required for an mcml built from a matrix, an edge list, a netobject or a tna model, which keep no usable node-level source; without it an error is raised. Default NULL.

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 net_bayes from bayes_compare(), or a netdifference, which is returned as it is. Any other object raises an error.

...

Not used.

significant_only

For a net_bayes: whether the drawn weights keep only the credible differences (those bayes_compare() marks in sig), with every other edge set to 0. The full difference and interval matrices are kept either way. Default TRUE.

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 psychnet object, a cograph_network, a netobject, or a tna model or group_tna (package tna). Any other object raises an error.

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

validate_netobject

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 mcml_pc fit from build_mcml_pc(), or a netobject_group, which is returned unchanged. Any other object raises an error.

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 mcml object from cluster_summary() or build_mcml(). The default method also takes a tna model.

...

Not used.

expand

For the mcml method: clusters whose member states replace the collapsed cluster node in the macro network, as in macro_network(). Default NULL (the macro network stays fully collapsed). The within-cluster networks are not affected. It needs an mcml that build_mcml() built from a wide sequence frame, a sequence matrix or an event log; one from cluster_summary(), an edge list, a netobject or a tna model raises an error of class nestimate_no_expand_source.

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:

netobject

Each sequence in its data becomes a transaction of its distinct states. In a one-hot network the codes are the items and each window is one transaction. A network without data, and an association network (cor, pcor, glasso, ising, mgm), whose rows are variables, raise an error; a netobject_group raises one of class nestimate_bad_input (pass one group's network). A bare cograph_network is read as a netobject, a tna model by its sequence data, and an mcml by its between-cluster network, so its items are the clusters.

list

A plain list holding one character vector of items per transaction.

data frame

Each row is a transaction of its distinct non-missing states. The frame must be a single column or a numbered run of position columns (T1, T2, ...) with nothing beside it; otherwise it raises an error of class nestimate_bad_input; declare the columns with build_network(state_cols = ) and pass the network instead. A column called action and repeated column names are refused the same way. A frame of 0/1 or logical columns is a binary table, one column per item, read with format = "binary".

matrix

A character matrix is read like a character data frame. A numeric or logical matrix is a binary transaction table (rows are transactions, columns are items, named I1, I2, ... when the matrix has no column names).

Binary input must hold only 0/1 or TRUE/FALSE: a missing cell, any other value or two columns with one name raises an error of class nestimate_bad_input. Input with no transaction (a one-hot network with no complete window) gives an empty result. For the print() and plot() methods: a net_association_rules object.

min_support

The smallest share of transactions an itemset must occur in to be frequent, above 0 and at most 1. Default 0.1. It is applied as a count, ceiling(min_support * n_transactions).

min_confidence

The smallest confidence a rule must have, between 0 and 1. Default 0.5.

min_lift

The smallest lift a rule must have, at least 0. Default 1, which keeps rules whose items occur together at least as often as independence predicts.

max_length

The largest itemset size searched, at least 2. Default 5.

format

How 0/1 columns are read. Columns of only 0 and 1 could be items or recoded positions, so with "auto" (default) they raise an error of class nestimate_bad_input. "binary" declares them items, one row per transaction; it raises the same error on a data frame with any other value. A list of transactions or a network has no 0/1 columns, so "binary" is ignored for them with a warning of class nestimate_ignored_argument.

...

For the print(), summary() and plot() methods: ignored.

object

For the summary() method: a net_association_rules object.

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 antecedent and consequent (the itemsets as comma-separated strings), support, confidence, lift, conviction, count (transactions holding the whole rule) and n_transactions.

frequent

Data frame, one row per frequent itemset, with columns itemset, size, support and count.

frequent_itemsets

List of the frequent itemsets per size k, each entry a list of items, count and support.

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_lift and max_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

build_network, predict_links

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 netobject estimated with "relative" or "frequency" or one of their aliases, a netobject_group, or a net_edge_betweenness object. A bare cograph_network is recounted from the sequences it carries, and used only when they reproduce its weights; otherwise, and for an mcml, an error of class nestimate_bad_input is raised. Both networks must use the same method and hold the same nodes; any other method raises an error, because the model needs transition counts. A tna model or a group_tna (package tna) is first rebuilt as a network from its own sequences (see as_netobject()). For the print() and plot() methods: a net_bayes or a net_bayes_group.

y

The second network, of the same kind as x. Default NULL: with a netobject_group as x, every pair of its groups is compared. With two netobject_groups, the groups sharing a name are compared, and an error is raised when none do.

prior

The Dirichlet concentration added to every cell of the count matrices, a positive number. Default 0.5, the Jeffreys prior; 1 gives a uniform (Laplace) prior. Every cell gets it, so a transition observed in neither network still has a small posterior probability.

draws

The number of Monte Carlo posterior draws behind the credible intervals, at least 2. Default 10000. For edge-betweenness networks the betweenness is recomputed on every draw, so time grows with draws.

ci

The mass of the equal-tailed credible interval, a number between 0 and 1. Default 0.95.

mean_threshold

The absolute posterior mean difference an edge must exceed to be flagged as credibly different. Default 0.01, on the transition-probability scale.

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

seed

An integer that makes the draws reproducible; the session's own random stream is left as it was. Default NULL. For a group, it is set again before each comparison.

...

For plot(): further arguments for cograph::splot() when cograph is installed (such as weight_digits, the digits the drawn differences are rounded to, default 2, or edge_label_digits, the digits of the edge labels, default 3); otherwise ignored. The print() and summary() methods ignore it.

object

For summary(): a net_bayes or net_bayes_group.

significant_only

For plot(): whether to draw only the edges flagged as credibly different. Default TRUE. When no edge is left to draw, an error suggests significant_only = FALSE.

title

For plot(): the plot title. Default NULL, which gives "Bayesian network difference" (with cograph) or a title naming the posterior mean difference (without it).

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's netdifference helpers.

diff_sig

The difference where sig is TRUE, else 0.

p_values

The two-sided Bayesian p-equivalent, in the field a net_permutation consumer reads as p-values (see p_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-equivalent 2(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 a net_permutation summary (from, to, weight_x, weight_y, diff, effect_size, p_value, sig) plus count_x, count_y, ci_lower, ci_upper, ci_width and p_difference.

method, iter, alpha, paired, adjust

Permutation-compatible settings (iter = draws, alpha = 1 - ci, paired = FALSE, adjust = "none"); method is "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 simplicial_complex from build_simplicial(). When it was built with a max_dim below its largest clique, the top Betti number counts cycles whose filling simplices were not built, so it is an upper bound, and a warning of class nestimate_truncated_complex says so.

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, group and, when used, weight columns. Rows with a missing value in any of these columns are dropped without a message; when no row is left, an error is raised.

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 data raises an error, as for group and weight.

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 "10" comes before "2").

weight

The name of a numeric column summed per player and group to give a weighted incidence matrix. With the default NULL, the matrix is 0/1, and a player listed more than once in a group counts once. With weights, a player belongs to a group when the summed weight is positive; a group with no such member is dropped, and a player left without a group stays a node.

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:

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 as player, group and weight, and n_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 build_glasso(): non-numeric columns and a column named rid are set aside; columns with non-syntactic names, all-missing and constant columns, and rows with a missing value are dropped, each with a message; fewer than 2 variables or 3 complete rows, or no more rows than variables, raise an error. A square symmetric matrix with matching row and column names is read as a correlation or covariance matrix and refused (class nestimate_bad_input): it has no observations to resample. Or a netobject (or cograph_network) built with method = "glasso", whose data are resampled; any gamma, nlambda or cor_method set in its params replaces the arguments of the same name, and its lambda.min.ratio, penalize.diagonal, refit and threshold are used too, as is the network's own threshold when it has no scaling, so original_pcor is the network's weights (for a scaled network, its partial correlations before the scaling) and every resample is thresholded alike. Any other network raises an error. A correlation or covariance matrix is not accepted: a matrix is always read as data, its rows as observations. For the print() and plot() methods: a boot_glasso.

iter

The number of nonparametric bootstrap resamples, at least 2. Default 1000.

cs_iter

The total number of case-dropping iterations, at least 1. Default 500. As in bootnet, each iteration draws one proportion from cs_drop at random, so the iterations are spread across the proportions (about cs_iter / length(cs_drop) each) rather than repeated cs_iter times at each one.

cs_drop

The proportions of cases to drop, each in (0, 1). Default seq(0.1, 0.9, by = 0.1).

alpha

The significance level: the intervals run from the alpha / 2 to the 1 - alpha / 2 quantile, and print() and the "edge_diff" / "centrality_diff" plots mark the difference tests' p-values below it as differing. Default 0.05.

gamma

The EBIC hyperparameter; larger values give sparser networks. Default 0.5. For a netobject, the network's own value is used (the estimator's default when none is stored) and a different one is ignored with a warning of class nestimate_ignored_argument.

nlambda

The number of lambda values in the regularisation path, at least 2. Default 100. For a netobject, the network's own value, as for gamma.

centrality

The centrality measures to compute. Default all four built-in ones: "strength" (sum of absolute edge weights), "expected_influence" (sum of signed edge weights), "betweenness" and "closeness" (on shortest paths with distance 1 / |weight|). Without centrality_fn, names may be abbreviated. Any other name needs centrality_fn, which then computes it; the built-in measures are always computed internally.

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 list(my_metric = ...). Default NULL; a measure in centrality that is neither built in nor returned by it raises an error.

cor_method

The correlation method: "pearson" (default), "spearman" or "kendall". For a netobject, the network's own value, as for gamma.

ncores

The number of cores for the resampling, used through parallel::mclapply(), which forks the R process; on Windows it accepts only 1, and any larger value raises an error. Default 1 (sequential).

seed

A seed for reproducible resampling; the session's random state is restored when the call returns. Default NULL uses the current random stream. With ncores > 1 the resamples are reproducible only under RNGkind("L'Ecuyer-CMRG").

...

For the plot() method with type = "edge_diff" or "centrality_diff": order, "sample" (default) to sort the edges by their absolute weight or the nodes by their centrality, or "id" to sort them alphabetically; with type = "edge_diff" also pos_color and neg_color, the fills for a cell where the edge on the x-axis has a larger or a smaller mean bootstrap weight than the edge on the y-axis (defaults "#C0392B" and "#2C6E8A"). Ignored otherwise, and by the print() and summary() methods.

object

For the summary() method: a boot_glasso.

type

What to return or draw. For the summary() method: "edges" (default), the edge intervals sorted by decreasing absolute weight; "centrality", the centrality intervals; "cs", the case-dropping table; "predictability", the predictability intervals; or "all", the four together. For the plot() method: "edges" (default), each edge's weight and interval; "stability", the mean correlation with the original centralities against the proportion dropped, with a dashed line at 0.7; "edge_diff", a heatmap of the mean bootstrap difference between every pair of edges, faint where the pair does not differ at alpha and starred where it does, with the edge weights on the diagonal; "centrality_diff", a heatmap of which node pairs differ on measure, with the node values on the diagonal; or "inclusion", each edge's inclusion probability, with a dashed line at 0.5.

measure

For the plot() method with type = "centrality_diff": the centrality measure to compare, one of those computed (names may be abbreviated). Default NULL, the first measure computed.

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_upper and inclusion.

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) and n_samples (the iterations that drew that proportion).

edge_diff_p

A symmetric matrix of the edge-difference p-values; NULL when 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 iter x edges matrix of the bootstrap edge weights.

boot_centrality

A named list with one iter x nodes matrix of bootstrap values per centrality measure.

boot_predictability

An iter x 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_drop and statistics.

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

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 netobject that carries its data (any network from build_network()), or a cograph_network, which is converted first. A netobject_group or mcml bootstraps every network it holds (for an mcml, the macro network and each cluster's), and a wtna_mixed bootstraps both of its components (see Value). A tna model or a group_tna (package tna) is first rebuilt as a network from its own sequences (see as_netobject()). 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. A network without its data raises an error, and one that rests on a single sequence, or one-hot data with no actor or session, has nothing to resample and raises an error of class nestimate_single_sequence. A sequence network with no observed transition raises an error of class nestimate_no_transition, and a network built with level one of class nestimate_multilevel_resampling. For the print() methods: the result of bootstrap_network().

iter

The number of bootstrap replicates, at least 2. Default 1000.

ci_level

The significance level, between 0 and 1: the confidence intervals cover 1 - ci_level, and an edge is significant when its p-value is below ci_level. Default 0.05.

inference

The test behind the p-values. "stability" (default) counts the replicates outside the consistency range around the original weight; "threshold" counts the replicates whose absolute weight is below edge_threshold.

consistency_range

For inference = "stability": the two multipliers of the original weight that bound the consistency range. Default c(0.75, 1.25). For a negative weight the bounds are swapped, so the range still runs from the lower to the upper value. Not used by "threshold".

edge_threshold

For inference = "threshold": the absolute weight a replicate must reach. Default NULL, the 10th percentile of the non-zero absolute original weights. Not used by "stability".

seed

A number that makes the resamples reproducible. The session's own random stream is left as it was. For a netobject_group or mcml, each network is bootstrapped from the same seed; for a wtna_mixed, the seed is set once, before both components. Default NULL.

boundary

For inference = "stability": how a replicate that lands exactly on a bound of the consistency range counts. "inclusive" (default, as in tna) counts it as outside (\le / \ge); "strict" counts only replicates strictly outside (< / >).

ci_method

The confidence interval for the edge weights. "percentile" (default) uses the empirical bootstrap quantiles (Efron). "basic" reflects those quantiles around the observed weight, (2\hat{\theta} - q_{1-\alpha/2}, 2\hat{\theta} - q_{\alpha/2}) (Davison & Hinkley 1997, eq. 5.6), which corrects first-order bootstrap bias but can give bounds outside the natural weight range near its limits (for example below 0 for a transition probability close to 0).

actor

The column identifying the actor each sequence belongs to (for example "student_id" for sessions nested in students, "Group" for students nested in teams), looked up in the network's metadata or its wide sequence data. With it, whole actors are resampled; see Nested data and actor. Several column names, outermost first (such as c("Group", "Student")), are nested levels, of which the outermost is resampled; the reported number of actors, ICC and design effect are those of the outermost level, and levels that are not nested outermost first raise an error of class nestimate_bad_actor. Default NULL: sequences are resampled one by one. It is available for sequence-based transition networks ("relative", "frequency", "co_occurrence"); a method outside the fast path (see Details) raises an error of class nestimate_actor_unsupported. A value that is not one or more distinct column names, or whose outermost column names fewer than two actors, raises an error of class nestimate_bad_actor; a column that is absent or has missing values, one of class nestimate_actor_missing; and ids that do not give one actor per sequence, one of class nestimate_actor_misaligned.

...

For the print() and summary() methods: ignored.

object

For the summary() methods: the result of bootstrap_network().

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_lower and ci_upper, plus cr_lower and cr_upper with inference = "stability".

model

The pruned netobject, whose weights are significant: its non-significant edges, self-loops included, are zero. (The network net_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 actor column (or columns, outermost first) and the number of actors resampled (at the outermost level); NULL without actor.

clustering

Only with actor: a one-row data frame of n_sequences, n_actors, icc, icc_ci_lower, icc_ci_upper and deff_edges.

clustering_edges

Only with actor: one row per edge of summary, with from, to, icc, sd_actor, sd_sequence and deff.

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: persistent_homology() results, or data frames with the columns dimension, birth and death (other columns are ignored). Any other input, or a data frame missing one of those columns, raises an error.

dimension

The homology dimensions to compare, as whole numbers. Default NULL: every dimension that appears in either diagram. A dimension absent from both gives 0.

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 .Machine$double.eps ^ 0.5.

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 action set).

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). FALSE (default) adds none, TRUE adds one labelled "Start", and a single string adds one with that label. One-hot data, whose rows are time points rather than sequences, raises an error.

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 mark_terminal_state(), which fills all trailing missing cells with an absorbing state. FALSE (default), TRUE ("End") or a single string, as start.

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 or time_threshold; in one-hot data, each actor's rows. Default NULL.

action

The column holding each event's state; setting it declares the data an event log. Column names give no role: action, actor, time and session are read only when set. A column called Action with nothing declared raises an error of class nestimate_bad_input, and an undeclared time or session column beside action is named in a message of class nestimate_column_role. Default NULL.

time

The timestamp column of an event log. Events are ordered by it, and a gap longer than time_threshold starts a new sequence. Default NULL.

session

The column identifying sessions in an event log; each session is its own sequence, also without actor. Default NULL.

...

Further arguments for build_network(): format ("auto", "wide", "long" or "onehot", to force a reading of data), and for event logs prepare()'s time options unix_time_unit, is_unix_time and custom_format. method cannot be given: each alias has its own (error of class nestimate_bad_input).

order

The column that orders events sharing a timestamp; without it, those events keep their row order. Default NULL.

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. FALSE turns the split off, so each actor (or actor-session) is one sequence. Default 900.

timezone

The Olson time zone for timestamps without an offset (passed to prepare()); timestamps with an offset, such as ...Z or +02:00, are converted from it. Default "UTC".

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, T1, T2, ..., or 1, 2, ...); numeric columns beside the run and character or factor columns outside it are then covariates. Any other frame, and columns of only 0 and 1, raise an error of class nestimate_bad_input: nothing says whether they are positions or one-hot codes. Default NULL.

metadata_cols

Columns to keep as the network's metadata (covariates), never as positions; they cannot overlap state_cols. A column left out of a numbered run of positions is named in a message of class nestimate_column_role, and listing it here or in state_cols settles it. Default NULL.

lambda

The decay length: larger values let distant states count more. Default 1.

direction

"forward" (default) links each state to the later ones, "backward" to the earlier ones, and "both" to all.

decay

A function of ⁠(ti, tj, lambda)⁠ returning one weight per pair of positions, in place of the exponential decay. Default NULL.

group

A column to split the data by: one network per value, returned as a netobject_group. Default NULL.

scaling

Rescaling applied to the weights after estimation, in the order given: "minmax" rescales the weights to run from 0 to 1, over every cell for the transition methods (tna's rule, so with no zero cell the smallest weight becomes 0) and over the non-zero weights, into (0, 1], for the other methods, "max" divides by the largest absolute weight, "rank" replaces the non-zero weights by their ranks, and "normalize" makes each row's absolute weights sum to 1; an undirected network whose matrix it makes asymmetric becomes directed, so both of a pair's values are kept as edges. Zero weights stay zero under every option. Combine them as in c("rank", "minmax"). Default NULL (none).

threshold

Weights whose absolute value is below this are set to zero. Default 0 (none).

labels

New display labels for the nodes, applied after estimation: a two-column data frame (name, label), a named character vector c(name = "label") or a named list. It rewrites the node labels and the weight matrix's dimnames; nodes not listed keep their names. Default NULL.

params

Settings for the estimator, as a named list, as for build_tna(); also duration (one value per position, accumulated into times) or time_matrix (one row per sequence, one column per position), which measure the distance in time instead of positions. Default list().

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 netobject or bare cograph_network built from sequences with method "relative", "frequency", "co_occurrence" or "attention", whose stored sequences are used; or a tna model, whose integer-coded sequences are decoded to their labels. Columns of a data frame take the same roles as in build_network(): an id or a covariate is not a position, and the columns set aside are named in a message and kept as metadata. A one-hot network needs an actor or session to define its units. A one-hot network without one, and a network of any other method, raise an error of class nestimate_bad_input.

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. "hamming" (default) counts the positions where they differ. "lv" (Levenshtein) counts the insertions, deletions and substitutions that turn one into the other; "osa" (optimal string alignment) and "dl" (Damerau-Levenshtein) also count a swap of two adjacent states as one edit; "lcs" counts the states left unpaired by their longest common subsequence. "qgram", "cosine" and "jaccard" compare the runs of q consecutive states (q-grams) the sequences contain: the summed absolute difference of their counts, one minus the cosine similarity of the counts, and one minus the share of distinct q-grams they have in common. "jw" is the Jaro-Winkler distance, which weighs agreement in the first states more (see p).

method

The clustering algorithm. "pam" (default) partitions around medoids: it chooses k sequences as centres and assigns every sequence to the nearest one (Kaufman & Rousseeuw, 1990). "ward.D2", "ward.D", "complete", "average", "single", "mcquitty", "median" and "centroid" build a tree with stats::hclust() using that linkage and cut it into k groups.

na_syms

The symbols read as missing values, besides NA. Default c("*", "%"). A missing cell is not dropped from a comparison: it is treated as one more state, so two missing cells at the same position match and a missing cell against an observed state is a mismatch (a distance of 1 for Hamming). This is the usual rule for aligned sequences, because dropping missing cells pair by pair would change each pair's effective length and break the metric. For every dissimilarity except Hamming, a sequence ends at its last observed state, so trailing missing cells are not compared. To treat missing cells differently, drop or recode them before the call.

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). Default FALSE. With any dissimilarity other than "hamming", TRUE raises an error.

lambda

The decay rate of the position weights when weighted = TRUE: position t gets weight e^{-\lambda (t - 1)}, so a larger value puts more of the distance on the earlier positions. A finite non-negative number; default 1. Ignored, and stored as 0, when weighted = FALSE.

seed

An integer used as the random seed for clustering; the session's own random stream is left as it was. Default NULL. PAM and the hierarchical methods are deterministic, so it does not change the clusters; it is stored with the result.

q

The length of the q-grams compared by "qgram", "cosine" and "jaccard", a positive whole number. Default 2. Ignored by the other dissimilarities.

p

The Winkler prefix weight of "jw": how much agreement in the first states (up to four) lowers the Jaro distance, from 0 (the plain Jaro distance) to 0.25. Default 0.1. Ignored by the other dissimilarities.

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 ~ Age + Gender (or the string "Age + Gender"), or a data frame with one row per sequence, all of whose columns are used. For a netobject or cograph_network, names are looked up in its metadata first and then among the columns of its data, so a typical call is build_clusters(net, k = 3, covariates = "Achiever"); for a data frame or matrix, among its columns. A tna model takes only the data-frame form. Named covariate columns are taken out of the sequence data before the distances are computed, and so are the columns of a supplied data frame that match a sequence column in name and values; a sequence column that shares only a name is kept. For a network, a name found in its metadata leaves a same-named data column in place as a sequence position. Rows with a missing covariate are left out of the analysis with a warning, and a constant covariate raises an error. How the analysis is run is set by estimator. Default NULL (none).

estimator

How the relation between the covariates and the clusters is estimated; it never affects the clustering. "auto" (default) fits a multinomial logit of cluster membership on the covariates. When a cell of the cluster-by-covariate table of a categorical covariate holds fewer than 5 sequences, it uses Firth's bias-reduced penalised likelihood (package brglm2), which stays finite under quasi-complete separation; otherwise it uses maximum likelihood (package nnet). "firth" forces the Firth fit, which is about 200 times slower on well-conditioned data. "multinom" forces classical maximum likelihood and warns that rare cells can give extreme odds ratios with degenerate confidence intervals. "chisq" runs descriptive tests instead of a logit, as WeightedCluster does: for each categorical covariate a chi-square test with Cramer's V and standardised adjusted residuals, for each numeric one a Kruskal-Wallis test with eta-squared. Ignored without covariates.

...

Not used: an extra argument raises an error, here and in the print(), summary() and plot() methods for a net_clustering. print() of a tidy_covariates table ignores it.

x

For the print() and plot() methods: a net_clustering; for print(), also the tidy_covariates table that summary() returns.

digits

For print() of a net_clustering: decimal places of the silhouette width and the within-cluster distances, a non-negative whole number. Default 3.

object

For summary(): a net_clustering.

type

For plot(): the view. "silhouette" (default) draws each sequence's silhouette width as a bar, grouped by cluster, with the average as a dashed line; "mds" places the sequences on the first two dimensions of a classical multidimensional scaling of the distances, coloured by cluster; "heatmap" draws the distance matrix with the sequences ordered by cluster; "predictors" draws a forest plot of the covariates' odds ratios (log scale) for each cluster against the reference cluster. "predictors" needs a fit with covariates and a logit estimator; with estimator = "chisq", which has no odds ratios, it raises an error that points to summary() for the tests.

combined

For plot() with type = "predictors": TRUE (default) draws one plot with a panel per non-reference cluster; FALSE returns a list of plots, one per non-reference cluster. Ignored by the other views.

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

medoids

For PAM, the row numbers of the k medoid 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 when covariates = NULL.

network_method, build_args

For netobject input, 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_args holds only the settings that make its type in params (such as a co-occurrence network's type), or is NULL when it has none.

network_settings

For netobject input, the source network's threshold and scaling when they are not the defaults and its estimator settings in params, which build_network(x, inherit = TRUE) uses; NULL when there are none.

metadata

For netobject input, its per-sequence metadata, one row per clustered sequence, so session_ids can name each sequence. For a data frame, the columns set aside as covariates (see data). 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 action set), one-hot code columns (declared with codes), or a square matrix of transition counts or weights, which is row-normalised (every row needs a positive sum).

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). FALSE (default) adds none, TRUE adds one labelled "Start", and a single string adds one with that label. One-hot data, whose rows are time points rather than sequences, raises an error.

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 mark_terminal_state(), which fills all trailing missing cells with an absorbing state. FALSE (default), TRUE ("End") or a single string, as start.

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 or time_threshold; in one-hot data, each actor's rows. Default NULL.

action

The column holding each event's state; setting it declares the data an event log. Column names give no role: action, actor, time and session are read only when set. A column called Action with nothing declared raises an error of class nestimate_bad_input, and an undeclared time or session column beside action is named in a message of class nestimate_column_role. Default NULL.

time

The timestamp column of an event log. Events are ordered by it, and a gap longer than time_threshold starts a new sequence. Default NULL.

session

The column identifying sessions in an event log; each session is its own sequence, also without actor. Default NULL.

...

Further arguments for build_network(): format ("auto", "wide", "long" or "onehot", to force a reading of data), and for event logs prepare()'s time options unix_time_unit, is_unix_time and custom_format. method cannot be given: each alias has its own (error of class nestimate_bad_input).

order

The column that orders events sharing a timestamp; without it, those events keep their row order. Default NULL.

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. FALSE turns the split off, so each actor (or actor-session) is one sequence. Default 900.

timezone

The Olson time zone for timestamps without an offset (passed to prepare()); timestamps with an offset, such as ...Z or +02:00, are converted from it. Default "UTC".

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, T1, T2, ..., or 1, 2, ...); numeric columns beside the run and character or factor columns outside it are then covariates. Any other frame, and columns of only 0 and 1, raise an error of class nestimate_bad_input: nothing says whether they are positions or one-hot codes. Default NULL.

metadata_cols

Columns to keep as the network's metadata (covariates), never as positions; they cannot overlap state_cols. A column left out of a numbered run of positions is named in a message of class nestimate_column_role, and listing it here or in state_cols settles it. Default NULL.

codes

The one-hot code columns (one per state, 1 when the state is active); setting them declares one-hot data. Default NULL.

window_size

For one-hot data: how many consecutive rows form one window. Default 3. Windows on sequence data are set through params instead.

mode

For one-hot data: "non-overlapping" (default) or "overlapping" windows; build_wtna() describes how overlapping windows are counted.

type

"frequency" (default) keeps the counts; "relative" divides each row by its sum, which makes the network directed.

group

A column to split the data by: one network per value, returned as a netobject_group. Default NULL.

scaling

Rescaling applied to the weights after estimation, in the order given: "minmax" rescales the weights to run from 0 to 1, over every cell for the transition methods (tna's rule, so with no zero cell the smallest weight becomes 0) and over the non-zero weights, into (0, 1], for the other methods, "max" divides by the largest absolute weight, "rank" replaces the non-zero weights by their ranks, and "normalize" makes each row's absolute weights sum to 1; an undirected network whose matrix it makes asymmetric becomes directed, so both of a pair's values are kept as edges. Zero weights stay zero under every option. Combine them as in c("rank", "minmax"). Default NULL (none).

threshold

Weights whose absolute value is below this are set to zero. Default 0 (none).

labels

New display labels for the nodes, applied after estimation: a two-column data frame (name, label), a named character vector c(name = "label") or a named list. It rewrites the node labels and the weight matrix's dimnames; nodes not listed keep their names. Default NULL.

params

Settings for the estimator, as a named list. Transitions are counted with tna's weighted and concat options, and window_size (with window_span, or windowed = TRUE for a size of 2) counts them between consecutive non-overlapping blocks of that many positions, as tna::tna() does; mode = "overlapping" then raises a warning of class nestimate_ignored_mode. The network keeps these settings, and the resampling verbs such as bootstrap_network() re-estimate with them. Default list().

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 params (as in params = list(n = 250)). Non-numeric columns are set aside; a frame of two or more character or factor columns and fewer than two numeric ones is read as sequences and turned into per-row state counts first. A column named rid is set aside; columns with non-syntactic names, all-missing and constant columns, and rows with a missing value are dropped, each with a message; fewer than 2 variables or 3 complete rows raise an error.

actor

The id column naming whose observation each row is (a person). With level, the decomposition groups by it; without, it is set aside, not modelled. Default NULL.

level

Multilevel decomposition, with actor: "between" estimates the network of person means, "within" the network of deviations from them, and "both" returns the two as a netobject_ml. Default NULL (no decomposition).

...

Further arguments for build_network(). method cannot be given (error of class nestimate_bad_input).

cor_method

"pearson" (default), "spearman" or "kendall", passed to stats::cor().

predictability

Whether to compute each node's predictability (the R-squared of the node on its neighbours). It is stored on the network, and cograph::splot() draws it as a ring around each node. Default TRUE.

metadata_cols

Columns to keep as the network's metadata (covariates), never read as variables. Default NULL.

group

A column to split the data by: one network per value, returned as a netobject_group. Default NULL.

scaling

Rescaling applied to the weights after estimation, in the order given: "minmax" rescales the weights to run from 0 to 1, over every cell for the transition methods (tna's rule, so with no zero cell the smallest weight becomes 0) and over the non-zero weights, into (0, 1], for the other methods, "max" divides by the largest absolute weight, "rank" replaces the non-zero weights by their ranks, and "normalize" makes each row's absolute weights sum to 1; an undirected network whose matrix it makes asymmetric becomes directed, so both of a pair's values are kept as edges. Zero weights stay zero under every option. Combine them as in c("rank", "minmax"). Default NULL (none).

threshold

Weights whose absolute value is below this are set to zero. Default 0 (none).

labels

New display labels for the nodes, applied after estimation: a two-column data frame (name, label), a named character vector c(name = "label") or a named list. It rewrites the node labels and the weight matrix's dimnames; nodes not listed keep their names. Default NULL.

params

Settings for the estimator, as a named list, such as n, the sample size when data is a correlation or covariance matrix. The network stores them, so bootstrap_network() re-estimates with the same settings. Default list().

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 action set), one-hot code columns (declared with codes), or a square matrix of transition counts or weights, which is row-normalised (every row needs a positive sum).

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). FALSE (default) adds none, TRUE adds one labelled "Start", and a single string adds one with that label. One-hot data, whose rows are time points rather than sequences, raises an error.

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 mark_terminal_state(), which fills all trailing missing cells with an absorbing state. FALSE (default), TRUE ("End") or a single string, as start.

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 or time_threshold; in one-hot data, each actor's rows. Default NULL.

action

The column holding each event's state; setting it declares the data an event log. Column names give no role: action, actor, time and session are read only when set. A column called Action with nothing declared raises an error of class nestimate_bad_input, and an undeclared time or session column beside action is named in a message of class nestimate_column_role. Default NULL.

time

The timestamp column of an event log. Events are ordered by it, and a gap longer than time_threshold starts a new sequence. Default NULL.

session

The column identifying sessions in an event log; each session is its own sequence, also without actor. Default NULL.

...

Further arguments for build_network(): format ("auto", "wide", "long" or "onehot", to force a reading of data), and for event logs prepare()'s time options unix_time_unit, is_unix_time and custom_format. method cannot be given: each alias has its own (error of class nestimate_bad_input).

order

The column that orders events sharing a timestamp; without it, those events keep their row order. Default NULL.

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. FALSE turns the split off, so each actor (or actor-session) is one sequence. Default 900.

timezone

The Olson time zone for timestamps without an offset (passed to prepare()); timestamps with an offset, such as ...Z or +02:00, are converted from it. Default "UTC".

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, T1, T2, ..., or 1, 2, ...); numeric columns beside the run and character or factor columns outside it are then covariates. Any other frame, and columns of only 0 and 1, raise an error of class nestimate_bad_input: nothing says whether they are positions or one-hot codes. Default NULL.

metadata_cols

Columns to keep as the network's metadata (covariates), never as positions; they cannot overlap state_cols. A column left out of a numbered run of positions is named in a message of class nestimate_column_role, and listing it here or in state_cols settles it. Default NULL.

codes

The one-hot code columns (one per state, 1 when the state is active); setting them declares one-hot data. Default NULL.

window_size

For one-hot data: how many consecutive rows form one window. Default 3. Windows on sequence data are set through params instead.

mode

For one-hot data: "non-overlapping" (default) or "overlapping" windows; build_wtna() describes how overlapping windows are counted.

group

A column to split the data by: one network per value, returned as a netobject_group. Default NULL.

scaling

Rescaling applied to the weights after estimation, in the order given: "minmax" rescales the weights to run from 0 to 1, over every cell for the transition methods (tna's rule, so with no zero cell the smallest weight becomes 0) and over the non-zero weights, into (0, 1], for the other methods, "max" divides by the largest absolute weight, "rank" replaces the non-zero weights by their ranks, and "normalize" makes each row's absolute weights sum to 1; an undirected network whose matrix it makes asymmetric becomes directed, so both of a pair's values are kept as edges. Zero weights stay zero under every option. Combine them as in c("rank", "minmax"). Default NULL (none).

threshold

Weights whose absolute value is below this are set to zero. Default 0 (none).

labels

New display labels for the nodes, applied after estimation: a two-column data frame (name, label), a named character vector c(name = "label") or a named list. It rewrites the node labels and the weight matrix's dimnames; nodes not listed keep their names. Default NULL.

params

Settings for the estimator, as a named list. Transitions are counted with tna's weighted and concat options, and window_size (with window_span, or windowed = TRUE for a size of 2) counts them between consecutive non-overlapping blocks of that many positions, as tna::tna() does; mode = "overlapping" then raises a warning of class nestimate_ignored_mode. The network keeps these settings, and the resampling verbs such as bootstrap_network() re-estimate with them. Default list().

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 action set).

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). FALSE (default) adds none, TRUE adds one labelled "Start", and a single string adds one with that label. One-hot data, whose rows are time points rather than sequences, raises an error.

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 mark_terminal_state(), which fills all trailing missing cells with an absorbing state. FALSE (default), TRUE ("End") or a single string, as start.

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 or time_threshold; in one-hot data, each actor's rows. Default NULL.

action

The column holding each event's state; setting it declares the data an event log. Column names give no role: action, actor, time and session are read only when set. A column called Action with nothing declared raises an error of class nestimate_bad_input, and an undeclared time or session column beside action is named in a message of class nestimate_column_role. Default NULL.

time

The timestamp column of an event log. Events are ordered by it, and a gap longer than time_threshold starts a new sequence. Default NULL.

session

The column identifying sessions in an event log; each session is its own sequence, also without actor. Default NULL.

order

The column that orders events sharing a timestamp; without it, those events keep their row order. Default NULL.

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. FALSE turns the split off, so each actor (or actor-session) is one sequence. Default 900.

timezone

The Olson time zone for timestamps without an offset (passed to prepare()); timestamps with an offset, such as ...Z or +02:00, are converted from it. Default "UTC".

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, T1, T2, ..., or 1, 2, ...); numeric columns beside the run and character or factor columns outside it are then covariates. Any other frame, and columns of only 0 and 1, raise an error of class nestimate_bad_input: nothing says whether they are positions or one-hot codes. Default NULL.

metadata_cols

Columns to keep as the network's metadata (covariates), never as positions; they cannot overlap state_cols. A column left out of a numbered run of positions is named in a message of class nestimate_column_role, and listing it here or in state_cols settles it. Default NULL.

max_gap

How many states may lie between the two states of a pair, a whole number of at least 0. Default 1.

group

A column to split the data by: one network per value, returned as a netobject_group. Default NULL.

scaling

Rescaling applied to the weights after estimation, in the order given: "minmax" rescales the weights to run from 0 to 1, over every cell for the transition methods (tna's rule, so with no zero cell the smallest weight becomes 0) and over the non-zero weights, into (0, 1], for the other methods, "max" divides by the largest absolute weight, "rank" replaces the non-zero weights by their ranks, and "normalize" makes each row's absolute weights sum to 1; an undirected network whose matrix it makes asymmetric becomes directed, so both of a pair's values are kept as edges. Zero weights stay zero under every option. Combine them as in c("rank", "minmax"). Default NULL (none).

threshold

Weights whose absolute value is below this are set to zero. Default 0 (none).

labels

New display labels for the nodes, applied after estimation: a two-column data frame (name, label), a named character vector c(name = "label") or a named list. It rewrites the node labels and the weight matrix's dimnames; nodes not listed keep their names. Default NULL.

params

Settings for the estimator, as a named list, as for build_tna(); also duration (one value per position, accumulated into times) or time_matrix (one row per sequence, one column per position), which measure the distance in time instead of positions. Default list().

...

Further arguments for build_network(): format ("auto", "wide", "long" or "onehot", to force a reading of data), and for event logs prepare()'s time options unix_time_unit, is_unix_time and custom_format. method cannot be given: each alias has its own (error of class nestimate_bad_input).

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:

  1. 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 default 0.75, of the people whose models converged).

  2. 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 data; a missing name raises an error.

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 id and then time before the lagged variables are formed; with NULL (default), the row order is used.

ar

Whether each variable's autoregressive path (itself at lag 1) is fixed into every model. Default TRUE.

standardize

Whether the variables are standardised within each person before estimation. Default FALSE. The coefficients come from lavaan's standardised solution either way, so this changes only the scale-dependent fit statistics (the log-likelihood, AIC and BIC); the chi-square, RMSEA, SRMR, NNFI and CFI do not change.

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

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

paths

Paths, in lavaan syntax, to fix into every model, such as "V2~V1lag". Default NULL.

exogenous

The variables treated as exogenous (predictors only), all among vars; at least one variable must remain endogenous, and either rule broken raises an error. Default NULL.

hybrid

Whether the search also considers residual covariances between the variables at the same time point. Default FALSE.

rmsea_cutoff

The RMSEA at or below which a person's fit counts as excellent. Default 0.05.

srmr_cutoff

The SRMR at or below which a person's fit counts as excellent. Default 0.05.

nnfi_cutoff

The NNFI (TLI) at or above which a person's fit counts as excellent. Default 0.95.

cfi_cutoff

The CFI at or above which a person's fit counts as excellent. Default 0.95.

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

seed

An integer that makes the estimation reproducible; the session's own random stream is left as it was. Default NULL.

x

For the coefs() method: a net_gimme from build_gimme().

...

For the coefs() method: passed to idiographic::coefs().

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:

temporal

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

contemporaneous

p 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_avg

p x p group-average coefficient matrices.

coefs

List of per-person p x 2p coefficient matrices (rows the endogenous variables, columns the lagged and then the contemporaneous variables).

psi

List of per-person residual covariance matrices.

fit

Data frame of per-person fit indices (file, the person, then chisq, df, pvalue, rmsea, srmr, nnfi, cfi, bic, aic, logl and status).

path_counts

p x 2p matrix: how many people have each path.

paths

List of per-person character vectors of lavaan path syntax.

group_paths

Character vector of the group-level paths found.

individual_paths

List of per-person character vectors of the individual-level paths (beyond the group paths).

syntax

List of per-person full lavaan syntax strings.

labels

Character vector of variable names.

n_subjects

Number of people.

n_obs

Integer vector of the lagged time points per person (its rows minus one).

config

List 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

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

build_network

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 params (as in params = list(n = 250)). Non-numeric columns are set aside; a frame of two or more character or factor columns and fewer than two numeric ones is read as sequences and turned into per-row state counts first. A column named rid is set aside; columns with non-syntactic names, all-missing and constant columns, and rows with a missing value are dropped, each with a message; fewer than 2 variables or 3 complete rows raise an error.

actor

The id column naming whose observation each row is (a person). With level, the decomposition groups by it; without, it is set aside, not modelled. Default NULL.

level

Multilevel decomposition, with actor: "between" estimates the network of person means, "within" the network of deviations from them, and "both" returns the two as a netobject_ml. Default NULL (no decomposition).

...

Further arguments for build_network(). method cannot be given (error of class nestimate_bad_input).

gamma

The EBIC hyperparameter: larger values give sparser networks. Default 0.5.

nlambda

The number of penalties tried. Default 100.

cor_method

"pearson" (default), "spearman" or "kendall", passed to stats::cor().

predictability

Whether to compute each node's predictability (the R-squared of the node on its neighbours). It is stored on the network, and cograph::splot() draws it as a ring around each node. Default TRUE.

metadata_cols

Columns to keep as the network's metadata (covariates), never read as variables. Default NULL.

group

A column to split the data by: one network per value, returned as a netobject_group. Default NULL.

scaling

Rescaling applied to the weights after estimation, in the order given: "minmax" rescales the weights to run from 0 to 1, over every cell for the transition methods (tna's rule, so with no zero cell the smallest weight becomes 0) and over the non-zero weights, into (0, 1], for the other methods, "max" divides by the largest absolute weight, "rank" replaces the non-zero weights by their ranks, and "normalize" makes each row's absolute weights sum to 1; an undirected network whose matrix it makes asymmetric becomes directed, so both of a pair's values are kept as edges. Zero weights stay zero under every option. Combine them as in c("rank", "minmax"). Default NULL (none).

threshold

Weights whose absolute value is below this are set to zero. Default 0 (none).

labels

New display labels for the nodes, applied after estimation: a two-column data frame (name, label), a named character vector c(name = "label") or a named list. It rewrites the node labels and the weight matrix's dimnames; nodes not listed keep their names. Default NULL.

params

Settings for the estimator, as a named list: lambda.min.ratio (default 0.01), penalize.diagonal (default FALSE), refit (default FALSE; TRUE re-estimates the selected edges without the penalty), and n, the sample size when data is a correlation or covariance matrix. The network stores them, so the resampling verbs re-estimate with the same settings. Default 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 (T1, T2, ...), or be a sequence table returned by a Nestimate verb such as extract_sequences(), and any other frame raises an error of class nestimate_bad_input (declare its positions with build_network(state_cols = ) and pass the network). A plain list holds one vector of states per sequence. A netobject, a bare cograph_network or a tna built from sequences contributes its stored sequences, with a tna's numeric state codes converted to their labels. Values are read as character. A missing value ends a run of observed states, so a sequence with an internal gap becomes two sequences, and sequences with fewer than two states are dropped; when none is left, an error is raised. A one-hot or association network, a netobject_group, a classed list, and a matrix or data frame of only 0 and 1 raise an error of class nestimate_bad_input. A state whose label contains " -> ", the separator of the node names, also raises nestimate_bad_input: the state "A -> B" and the node of B reached from A would be one node.

max_order

The highest order a node may reach, that is, how many states of history it carries. Default 5. Lower orders result where the data do not support a longer history; print() reports the highest order reached beside the one requested. Must be at least 1; a fractional value is truncated to a whole number.

min_freq

The minimum count for a transition to be used. Transitions observed fewer than min_freq times are treated as zero, also in the totals that set the divergence threshold. Default 1. Must be at least 1; a fractional value is truncated to a whole number.

collapse_repeats

Whether to collapse each run of a repeated state into one state before counting (after splitting at missing values). Default FALSE.

method

The algorithm. "hon+" (default) is BuildHON+, which counts a longer history only when it is needed and skips an extension when even the largest divergence the history could reach would not pass the threshold. "hon" is the original BuildHON, which first counts the transitions from every history of up to max_order states. Both stop at max_order.

x

For the print() method: a net_hon.

...

Ignored by the print() and summary() methods.

object

For the summary() method: a net_hon.

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:

  1. Count the transitions from every history of up to max_order states (subsequences of up to max_order + 1 states); BuildHON+ counts the longer histories only when they are needed.

  2. Turn the counts into next-state distributions, setting counts below min_freq to zero.

  3. 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), where order is the new order and n the number of transitions counted from the longer history (after setting counts below min_freq to zero).

  4. 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: weights is the cograph_network field, matrix the 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), and from_order and to_order (the orders of the source and target nodes).

edges

The cograph_network edge table: one row per non-zero cell of weights, with integer from/to indices into nodes and a numeric weight. It is not the arrow-notation table, which is ho_edges.

nodes

A data frame with columns id, label and name, one row per node; label and name hold 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_order used.

max_order_observed

The highest order reached.

min_freq

The min_freq used.

n_trajectories

The number of sequences analysed, after splitting at missing values and dropping short ones.

directed

Always TRUE.

meta

The cograph_network metadata list (source, layout, and tna$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 net_hon object from build_hon(), or a square weighted adjacency matrix with at least 2 rows. Anything else raises an error.

dim

The number of embedding dimensions. Default 32. It is capped at the number of nodes minus 1 without a warning; print() reports the dimension used.

max_power

L, the upper limit of k in the decayed sum, at least 1. Default 10. The sum runs from D^1 to D^{L+1}, so the highest matrix power is max_power + 1. Higher values let longer paths shape the proximities.

x

For the print() and plot() methods: a net_honem object.

...

For the plot() method: further arguments passed to graphics::plot(). For the print() and summary() methods: ignored.

object

For the summary() method: a net_honem object.

dims

For the plot() method: the two dimensions to draw. Default c(1, 2); a dimension the embedding does not have raises an error. Nodes are labelled when there are at most 50; an embedding with a single dimension draws nothing and says so in a message.

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 columns dim_1, dim_2, ...

nodes

Character vector of node names.

singular_values

The dim leading 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 of k; the highest matrix power used is max_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 tna model, or a netobject built from sequences. For a tna model or a netobject, numeric state codes are converted to their labels. A frame with other columns beside the positions, a frame or matrix of only 0 and 1, a netobject_group, and a one-hot or association network raise an error of class nestimate_bad_input.

order

The order or orders of the De Bruijn graph, whole numbers of at least 1 without duplicates. Default 2. Order k tests paths of k + 1 states (k transitions), each conditioned on the k-state context before its last state. With several orders, one layer is built per order, in ascending order whatever the order given; an order with no paths (longer than the sequences allow) is dropped with a warning of class nestimate_ignored_argument, and an error is raised when none is left. The network fields (weights, edges, adjacency, xi, nodes, meta) describe the lowest order built, while scores holds every order.

alpha

The significance threshold for the labels, a number in (0, 0.5). Default 0.05. A path is under-represented when its adjusted lower-tail p-value (p_adjusted_under) is below alpha, otherwise over-represented when its adjusted upper-tail p-value (p_adjusted_over) is at most alpha, and normal otherwise.

min_count

The smallest count a path needs to be labelled, a whole number of at least 1. Default 5. An over-represented path must be observed at least min_count times, an under-represented path expected at least min_count times under the null model, so a path that never occurs can still be under-represented. Paths below it are normal.

p_adjust

The correction of the p-values for multiple testing: any of stats::p.adjust.methods, such as "BH" for Benjamini-Hochberg false discovery rate control. Default "none", which compares the raw p-values with alpha, as LaRock et al. (2020) do. Under- and over-representation p-values are adjusted separately, within each order, over every possible path. With small counts the paper's upper-tail score P(X > f) rejects more often than alpha under the null, so neither the raw nor the corrected labels carry an exact type-I error or false discovery rate guarantee; min_count limits the problem.

k

The former name of order, deprecated: when given, it replaces order, with a warning of class deprecatedWarning. Default NULL.

x

For the print() method: a net_hypa.

...

For the print() and summary() methods: ignored.

object

For the summary() method: a net_hypa.

n

For the summary() method: the most paths to show and return per direction. Default 10.

type

For the summary() method: which anomalies to show, "all" (default), "over" or "under".

order_by

For the summary() method: how the paths are ranked within each direction before the top n are kept. "sig" (default) ranks by the tail probability of that direction, "freq" (or "frequency") by observed count, "ratio" by observed / expected (highest first for over-represented paths, lowest first for under-represented ones), and "path" alphabetically. With type = "all" the returned rows of both directions are ranked together the same way, by how far the ratio is from 1 on the log scale (abs(log(ratio))) for "ratio".

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 expectation n(a b \cdot) n(\cdot b c) / n(\cdot b \cdot)), from the continuous fit; ratio, observed / expected; p_under, the hypergeometric lower-tail probability P(X <= observed), whose pool sizes are the propensities rounded to whole numbers, as the hypergeometric distribution requires, so its mean can differ from expected by up to about 0.5 / m for m observed paths of that order; and p_value, the same value under its older name; p_over, the strict upper tail P(X > observed) = 1 - p_under, so that p_over <= alpha is the paper's HYPA score of at least 1 - alpha; p_adjusted_under and p_adjusted_over, the same after p_adjust; anomaly ("over", "under" or "normal"); and order.

ho_edges

The same table as scores, under the name the other higher-order builders use.

over, under

The rows of scores labelled 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; label and name are the node's k states joined by the internal separator "\x01", as are the dimnames of adjacency, weights and xi.

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 netobject, bare cograph_network, simplicial_complex (its edges are read as ties of weight 1 and the cliques are found again up to max_size), or a numeric or logical adjacency or weight matrix (nodes are named V1, V2, ... when it has no row names). A tie counts in either direction, so a directed network is symmetrised, and self-loops are ignored. A tna model (package tna) is first rebuilt as a network from its own sequences (see as_netobject()).

p

The probability that each clique of 3 or more nodes becomes a hyperedge, a number in ⁠[0, 1]⁠; each clique is kept or dropped independently. Default 1 (every clique is kept). Pairwise edges are not sampled.

method

How hyperedges are found. "clique" (default) promotes the cliques of the thresholded network. "vr" and "rips" (a metric Vietoris-Rips construction) are not implemented and raise an error instead of falling back to "clique".

include_pairwise

Whether the pairwise edges of the thresholded network become hyperedges of size 2. FALSE gives a hypergraph of hyperedges of size 3 or more only. Default TRUE.

max_size

The largest hyperedge size, at least 2. Default 3 (triangles); 4 adds the 4-cliques, and so on. With 2, only the pairwise edges remain (none, with include_pairwise = FALSE).

threshold

The cut-off that turns weights into ties: an edge is kept when its absolute weight is non-zero and at least threshold, so negative weights count by their size. A negative value raises an error. Default 0 (every non-zero weight is a tie).

seed

An integer that makes the sampling reproducible when ⁠0 < p < 1⁠. The session's own random stream is left as it was. Default NULL.

x

For the print() method: a net_hypergraph.

...

Not used.

object

For the summary() method: a net_hypergraph.

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:

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:

hyperedges

A list of integer vectors, one per hyperedge, each the sorted indices of the nodes it spans; pairwise edges, when kept, come first.

incidence

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

nodes

The node names.

n_nodes, n_hyperedges

The numbers of nodes and hyperedges.

size_distribution

A named integer vector with the number of hyperedges of each size, named size_2, size_3, ...

params

The settings used: method, p, include_pairwise, max_size, threshold and seed.

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 rid are set aside; columns with non-syntactic names, all-missing and constant columns, and rows with a missing value are dropped, each with a message; fewer than 2 variables or 3 complete rows, or any value other than 0 and 1, raise an error.

actor

An id column naming whose observation each row is; it is set aside, not modelled. Default NULL.

...

Further arguments for build_network(). method cannot be given (error of class nestimate_bad_input).

gamma

The EBIC hyperparameter. Default 0.25.

nlambda

The number of penalties tried. Default 100.

rule

"AND" (default) keeps an edge when both regressions select it, "OR" when either does.

metadata_cols

Columns to keep as the network's metadata (covariates), never read as variables. Default NULL.

group

A column to split the data by: one network per value, returned as a netobject_group. Default NULL.

scaling

Rescaling applied to the weights after estimation, in the order given: "minmax" rescales the weights to run from 0 to 1, over every cell for the transition methods (tna's rule, so with no zero cell the smallest weight becomes 0) and over the non-zero weights, into (0, 1], for the other methods, "max" divides by the largest absolute weight, "rank" replaces the non-zero weights by their ranks, and "normalize" makes each row's absolute weights sum to 1; an undirected network whose matrix it makes asymmetric becomes directed, so both of a pair's values are kept as edges. Zero weights stay zero under every option. Combine them as in c("rank", "minmax"). Default NULL (none).

threshold

Weights whose absolute value is below this are set to zero. Default 0 (none).

labels

New display labels for the nodes, applied after estimation: a two-column data frame (name, label), a named character vector c(name = "label") or a named list. It rewrites the node labels and the weight matrix's dimnames; nodes not listed keep their names. Default NULL.

params

Settings for the estimator, as a named list. The network stores them, so the resampling verbs re-estimate with the same settings. Default list().

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

action

The column holding each message's sender.

time

The timestamp column. Events are ordered by it, and a gap longer than time_threshold starts a new sequence.

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 or time_threshold; in one-hot data, each actor's rows. Default NULL.

session

The column identifying sessions in an event log; each session is its own sequence, also without actor. Default NULL.

order

The column that orders events sharing a timestamp; without it, those events keep their row order. Default NULL.

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. FALSE turns the split off, so each actor (or actor-session) is one sequence. Default 900.

timezone

The Olson time zone for timestamps without an offset (passed to prepare()); timestamps with an offset, such as ...Z or +02:00, are converted from it. Default "UTC".

floor

The weight of a reply that takes cap or longer, a single number from 0 to 1. 1 ignores time (with aggregate = "sum", the counts of build_reverse()); 0 gives replies at or past the cap no weight. Default 0.5.

cap

The time at which a reply's weight reaches floor. A number in (0, 1] is a percentile of the latencies of the replies to another sender, pooled over all of data (with group, over every group, so the groups share one cap); a string such as "120s" is a number of seconds. The resolved cap, in seconds, is stored on the network. Default 0.95.

aggregate

How the replies of a pair of senders make one weight: "mean" (default) averages their weights, the pair's typical reply speed; "sum" adds them, so an edge grows with both the speed and the number of replies.

scope

With a percentile cap: the units that get their own cap. "global" (default) takes one cap from all of data; "actor" one per value of actor; "session" one per sequence; "responder" one per responding sender. A unit with fewer than 5 replies to another sender takes the global cap, and a message of class nestimate_latency_fallback says how many units did. A cap in seconds applies to every reply, so a scope other than "global" is then ignored with a message of class nestimate_ignored_argument.

group

A column to split the data by: one network per value, returned as a netobject_group. Default NULL.

scaling

Rescaling applied to the weights after estimation, in the order given: "minmax" rescales the weights to run from 0 to 1, over every cell for the transition methods (tna's rule, so with no zero cell the smallest weight becomes 0) and over the non-zero weights, into (0, 1], for the other methods, "max" divides by the largest absolute weight, "rank" replaces the non-zero weights by their ranks, and "normalize" makes each row's absolute weights sum to 1; an undirected network whose matrix it makes asymmetric becomes directed, so both of a pair's values are kept as edges. Zero weights stay zero under every option. Combine them as in c("rank", "minmax"). Default NULL (none).

threshold

Weights whose absolute value is below this are set to zero. Default 0 (none).

labels

New display labels for the nodes, applied after estimation: a two-column data frame (name, label), a named character vector c(name = "label") or a named list. It rewrites the node labels and the weight matrix's dimnames; nodes not listed keep their names. Default NULL.

...

Further arguments for build_network(): prepare()'s time options unix_time_unit, is_unix_time and custom_format. method cannot be given (error of class nestimate_bad_input).

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:

data frame with from and to set

An edge list: one row per transition, with an optional weight column.

data frame with action set

An event log, turned into sequences by prepare().

data frame of positions

Sequences, one row per sequence and one column per time step: either a numbered run of columns (T1, T2, ...) and nothing else, or the columns named in cols. Each pair of adjacent columns (t, t + 1) whose two states are both observed is a transition; a missing cell breaks the sequence.

tna model

Its stored sequences are decoded and counted; a model without data is passed to cluster_summary().

netobject or bare cograph_network

A network of a counting method (relative, frequency, co_occurrence and their aliases) is re-counted from the data it carries. A network of another method (such as an association or attention network), a one-hot network, or one without data is passed to cluster_summary(), which aggregates its weights.

mcml

Returned unchanged, unless clusters, combine or expand changes its partition: it is then re-estimated from the sequences it carries (see combine).

square numeric matrix

Passed to cluster_summary().

non-square or character matrix

Read as sequences.

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 nestimate_bad_input. For the print() methods: an mcml object or one of its layers (an mcml_layer).

clusters

The cluster of each state. Accepted forms:

named list

Cluster names mapped to their states, such as list(A = c("N1", "N2"), B = c("N3", "N4")).

data frame

State names in the first column, cluster names in the second, such as data.frame(node = c("N1", "N2", "N3"), group = c("A", "A", "B")).

membership vector

One cluster per state, such as c("A", "A", "B", "B"), matched to the states of the data in alphabetical order (a named vector is matched by name).

column name

For an edge list only: a column holding each row's cluster, given to both its endpoints. It suits edge lists whose edges never cross clusters; a node that gets two clusters raises an error, so pass a list or a data frame for any other edge list.

NULL

(default) Read from a netobject's node table (a column clusters, cluster, groups or group) or from its node_groups (aligned to the node table by label). The values are then taken in the order of the node table, which must list the states in the order build_network() gives them (alphabetical for sequence data). Other input needs an explicit assignment and raises an error without one.

Every state must belong to exactly one cluster, the end state included. On the sequence and edge-list routes the clusters of the result come in alphabetical order.

method

How the transitions between (or within) two clusters are combined into one weight, with net_aggregate_weights(): "sum" (default), "mean", "median", "max", "min", "density" or "geomean". On sequences and event logs every transition weighs 1, so only "sum" keeps the counts: "mean", "median", "max", "min" and "geomean" give 1 for every pair of clusters with a transition, and "density" divides each count by n_i * n_j. The other methods suit weighted edge lists and weight matrices, where each row is already a measurement rather than one observation. On sequences and event logs the within-cluster networks keep the counts under "sum" and "density" (which is not divided by n_i * n_j there) and get 1 for each observed pair of states under the other methods; on an edge list they hold the aggregated weights.

type

How the aggregated counts are turned into weights:

"tna"

(default) Each row is normalised to sum to 1, giving first-order Markov transition probabilities.

"raw"

The counts as they are.

"frequency"

The same counts as "raw", under the name frequency networks use.

"cooccurrence"

The mean of the count matrix and its transpose (undirected co-occurrence); the result is recorded as undirected.

"semi_markov" raises an error: the package has no semi-Markov (holding-time) construction. For input passed to cluster_summary() (a weight matrix, a tna model or netobject without data, or a netobject of a method that is not a count, such as "attention" or "glasso") type has no effect; setting it gives a warning for a matrix, or for a tna model or netobject without data.

directed

Whether transitions are directed. Default TRUE. FALSE replaces the counts by the mean of the count matrix and its transpose before type is applied.

compute_within

Whether to build the within-cluster networks. Default TRUE. An mcml built with FALSE keeps no per-cluster sequences, so it cannot be re-partitioned (see combine).

actor, action, time, order, session, time_threshold

For an event log: the columns and the session gap (in seconds, default 900) passed to prepare(), which forms the sequences that are then counted, as prepare(...) |> build_network() |> build_mcml() would. Setting action declares the data an event log.

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 NULL. Only for wide sequences and event logs: an edge list, a netobject or a tna model raises an error. The same holds for trim and end. On an existing mcml they raise an error together with a re-partition (clusters, combine or expand); without one the mcml is returned unchanged and they have no effect (see combine).

trim

How much of each sequence to keep. NULL (default) keeps every time step. A fraction in (0, 1) keeps the columns up to that quantile of the sequence lengths (the last observed position of each row), so trim = 0.95 cuts only the longest 5% of sequences; a value of 1 or more keeps that many leading columns (trim = 10 keeps the first 10). It changes the data, so it only ever cuts the end of a sequence; the fraction in sequence_plot()'s trim works differently because it changes only the drawing.

end

A terminal state put in the cell after each sequence's last observed state. FALSE (default) adds none, TRUE adds one labelled "End", and a single string adds one with that label; assign it to a cluster in clusters. It is added after trim, so trimming never removes it.

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, ⁠session = "AttemptID", end = "Conclude", end_by = "SkillID"⁠ closes each skill once, not each attempt. It needs end and an event log, and raises an error otherwise. Default NULL (every sequence is marked).

labels

New display labels for the states of the within-cluster networks, applied after estimation: a two-column data frame (name, label), a named character vector c(name = "label") or a named list. States not listed keep their names. The new labels also replace the state names in the cluster membership and the edge table; the macro network keeps its cluster names.

combine, expand

Change the partition. combine merges clusters into one: a character vector merges one group, and a list merges several, labelled by its names (default label "A + B"); the merged cluster lists its states in cluster-name order. expand then splits the named clusters (or every cluster, with "all" or TRUE) into one cluster per state, named by the state. On new input they apply to clusters (in any of its forms, auto-detection included) before estimation, so build_mcml(data, clusters = cl, combine = c("A", "B")) equals a build with A and B merged in cl; this works for every input, matrices included. On an existing mcml they re-estimate the model (macro network, within-cluster networks and stored sequences) from the sequences it carries, with its original type, method and directed unless these are passed; a new clusters does the same under that partition, and an unchanged partition returns an equal object. With none of clusters, combine and expand the mcml is returned as it is, and a shaping argument passed with it is ignored with a warning of class nestimate_ignored_argument. Any session split, exclude, trim or end applied at build time is already in those sequences, so passing one of them (or actor, action, time, order, session, time_threshold, end_by, labels, from, to, weight, cols) with a re-partition raises an error, as does passing clusters together with combine or expand. Raises nestimate_mcml_no_sequences on an mcml that keeps no sequences, such as one built from a matrix or an edge list. sequence_plot() takes the same two arguments as display options: its combine draws what it draws for build_mcml(x, combine = ), while its expand opens clusters in the Summary panel only and keeps one panel per cluster.

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 from and to are set, and setting them with action or cols raises an error of class nestimate_bad_input.

cols

For a wide data frame: the columns holding the positions, needed when the frame is anything but a numbered run (T1, T2, ...). Default NULL.

...

For the print() and summary() methods: not used; any extra argument raises an error.

object

For summary(): an mcml object.

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_to and type ("within" or "between").

macro

Its inits are the shares of the clusters among the first-column states (missing cells left out), or the normalised column sums for an edge list; its data holds the sequences recoded to cluster labels, or one from/to row per transition for an edge list.

clusters

Each layer counts only the transitions between states of its own cluster. Its inits are the shares of its states among the first-column states that belong to it (normalised column sums for an edge list), and its data the sequences with the states of other clusters set missing (for an edge list, its within-cluster transitions).

meta

source is "transitions", type records the type used, and directed whether the stored weights are directed (FALSE for type = "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 in method is 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 netobject (or a cograph_network) estimated with an undirected association method (cor, pcor, glasso, or their aliases), whose weights, stored data and method are reused; a directed network raises an error and points to build_mcml(). Or a numeric data frame of observations (one row per observation, one column per item), from which the node-level network is estimated with method and cor_method; a non-numeric column raises an error. Any other input, a matrix included, raises an error. For the print() and plot() methods: an mcml_pc object.

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 "scaled". The score paths re-estimate the network on one score per cluster and observation:

"scaled"

The weighted mean of the standardised member items.

"composite"

The former name of "scaled", kept as an alias.

"mean"

As "scaled", on the raw (unstandardised) items.

"median"

The row-wise median of the raw, sign-corrected items. The median is unweighted, so the weight magnitudes from weighting are not used, but a sign-carrying weighting still sets the item signs.

"loadings"

As "scaled", with the items weighted by their within-cluster network strength (weighting = "strength") unless weighting is given.

The descriptive ones relate the blocks without forming scores: "average" (the mean item-pair edge of each between-cluster block), "escoufier" (Escoufier's RV coefficient) and "cancor" (the first canonical correlation); the Description says how each can be read. Every path except "average" needs raw data; without it, an error suggests "average".

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: "pcor" (default), "glasso" or "cor", as in build_network(). When x is a cor, pcor or glasso netobject and method is not given, the netobject's own method is used; any other undirected netobject (an ising one, say) uses the default "pcor".

within

How the within-cluster networks are formed: "reestimate" (default) re-fits the estimator on each cluster's items, "subnetwork" slices the node-level weight matrix (see Details). Input without raw data uses "subnetwork" whatever is set.

weighting

How the items are weighted inside their cluster score on the score paths; on "median" only the signs of a sign-carrying scheme are used. Default "equal" ("strength" under aggregation = "loadings"); the descriptive aggregations ignore it, and their item table keeps the "strength" weights. The weights are absolute values normalised to sum to 1 within each cluster.

"equal"

1/m per item: the scale as scored.

"strength"

The item's mean absolute connection to the other members of its cluster in the node-level network (what aggregation = "loadings" selects), so items that anchor their cluster count more in its score. This is Nestimate's own weighting, related in spirit to network loadings (Christensen & Golino 2021) but not a reimplementation of any EGA-family estimator. A cluster whose within-cluster connections are all zero gets equal weights, with a warning.

"eigen"

The leading eigenvector of the cluster's block of the node-level network: like strength, with extra weight for items connected to other well-connected items.

"pca"

The first principal component of the member items' correlation matrix: a weighting from the data, blind to the estimated network. A correlation block with non-finite entries gives equal weights, with a warning.

"factor"

The standardised loadings of a one-factor model per cluster, the classical latent-variable weighting. fa_method sets the extraction and the correlations follow cor_method, so polychoric factor analysis of ordinal items is one call. A cluster with fewer than 3 items, or whose factor fit fails, falls back to "pca" with a warning.

"closeness", "betweenness"

The item's closeness or betweenness centrality within its cluster's block of the node-level network (absolute weights). Betweenness can be zero for every item of a densely connected cluster; equal weights are then used, with a warning, and the same holds for all-zero closeness.

"expected_influence"

The item's mean signed connection to the other members of its cluster (Robinaugh et al. 2016): like strength, but opposite-sign connections subtract, and a negative value marks a reverse-keyed item.

"specificity"

The misfit margin: own-cluster strength minus the strongest cross-cluster strength, floored at 0, so an item that belongs as much to another cluster adds nothing to its score; the weighting twin of the misfit flag. When no item of a cluster has a positive margin, equal weights are used, with a warning.

"item_total"

The corrected item-total correlation of each item with the mean of the other (standardised, sign-corrected) members: the classical scale-construction weighting.

weighting also takes a named numeric vector with one entry per item (its absolute values are normalised within each cluster and, when signed = TRUE, its signs set the item signs after the orientation described below), or a function ⁠function(W_block, data_block, nodes)⁠ that returns one finite weight per item, evaluated per cluster; a vector missing an item, or a function returning anything else, raises an error.

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 ("equal", "strength", "closeness", "betweenness", "specificity") keep the eigenvector-based item signs; the sign-carrying ones ("eigen", "pca", "factor", "expected_influence", "item_total", a custom vector or function) set the signs from their own values. Within each cluster those values are oriented first, negated when they sum to a negative number, so the sign carrying the larger total counts as positive and only the items of the other sign are flipped: marking the reverse-keyed items of a cluster negative works only when they do not outweigh the rest in total.

cor_method

The correlation used when estimating from raw data: "pearson" (default), "spearman" or "polychoric" (needs lavaan; see Details). For a network, the correlation it was estimated with, unless given. A network estimated with another correlation (such as "kendall") is read as it is when nothing is re-estimated, that is with within = "subnetwork" and any weighting but "factor"; otherwise it raises an error of class nestimate_bad_input unless cor_method is given.

signed

Whether reverse-keyed items are flipped in the cluster scores (see Details). Default TRUE.

id_col

Identifier columns to drop from data-frame input before the analysis. Default NULL. Use it for the id columns that convert_sequence_format() adds with format = "frequency", whose per-sequence counts otherwise feed this function directly as behaviour profiles. A rid column is left out of the node-level network without being listed, as in the association estimators of build_network(), except with cor_method = "polychoric", where it must be listed too; any other id column, including the .rid a wide table gets, is read as an item unless listed. A column not in the data raises an error; a netobject ignores the argument.

fa_method

The extraction method for weighting = "factor"; ignored otherwise.

"ml"

(default) Maximum likelihood, stats::factanal() on the correlation matrix that cor_method gives.

"paf"

Iterated principal axis factoring, starting from the squared multiple correlations and iterating the communalities on the reduced correlation matrix.

"minres"

Minimum residual (unweighted least squares): the uniquenesses are chosen to minimise the squared off-diagonal residuals.

"cfa"

A one-factor confirmatory model fitted with lavaan::cfa() (standardised loadings); with cor_method = "polychoric" the items are declared ordered, which gives the categorical (DWLS) factor model.

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 fa_method backend, spelled as that backend spells them, and allowed only with weighting = "factor" (otherwise they raise an error, as does an unnamed one): lavaan::cfa() arguments for "cfa" (estimator = "WLSMV", missing = "fiml", se = "robust", ...), stats::factanal() arguments for "ml", and max_iter / tol for "paf"; "minres" uses none. A name the backend does not read is dropped with a warning of class nestimate_ignored_argument. A "paf" or "minres" extraction that stops before converging keeps its last loadings and raises a warning of class nestimate_no_converge. estimator is lavaan's and raises an error for any other fa_method, since the network estimator is set by method. Arguments the backend call sets itself (model and data for "cfa"; covmat, n.obs, factors, x and data for "ml"; R for "paf" and "minres") are dropped with a warning: the model is always the one-factor model per cluster, because the score needs exactly one weight per item. For the print(), summary() and plot() methods: ignored.

digits

For the print() and plot() methods: the decimal places of the printed macro weights (default 3) or of the tile labels (default 2).

object

For the summary() method: an mcml_pc object.

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 (NULL for 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" and experimental = TRUE. method and weighting are NA on the descriptive paths, which re-estimate no macro network, and fa_method / fa_args are set only for weighting = "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

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, the decomposition groups by it; without, it is set aside, not modelled. Default NULL.

level

With actor, a multilevel decomposition ("between", "within" or "both"), as for build_cor(). A numeric vector instead gives one category count per modelled variable (1 for continuous ones); it is checked and kept for compatibility, and the fit reads the categories from the data. Default NULL.

lambdaGam

The EBIC hyperparameter. Default 0.25.

ruleReg

"AND" (default) keeps an edge when both regressions select it, "OR" when either does.

metadata_cols

Columns to keep as the network's metadata (covariates), never read as variables. Default NULL.

group

A column to split the data by: one network per value, returned as a netobject_group. Default NULL.

scaling

Rescaling applied to the weights after estimation, in the order given: "minmax" rescales the weights to run from 0 to 1, over every cell for the transition methods (tna's rule, so with no zero cell the smallest weight becomes 0) and over the non-zero weights, into (0, 1], for the other methods, "max" divides by the largest absolute weight, "rank" replaces the non-zero weights by their ranks, and "normalize" makes each row's absolute weights sum to 1; an undirected network whose matrix it makes asymmetric becomes directed, so both of a pair's values are kept as edges. Zero weights stay zero under every option. Combine them as in c("rank", "minmax"). Default NULL (none).

threshold

Weights whose absolute value is below this are set to zero (default 0); or "LW" or "none", mgm's rule for thresholding the coefficients (mgm's default is "LW").

labels

New display labels for the nodes, applied after estimation: a two-column data frame (name, label), a named character vector c(name = "label") or a named list. It rewrites the node labels and the weight matrix's dimnames; nodes not listed keep their names. Default NULL.

params

Settings for the estimator, as a named list. The network stores them. Default list().

...

Further arguments for build_network(). method cannot be given (error of class nestimate_bad_input).

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, id, day or beep that is not in it raises an error.

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

beep

The column numbering the measurement occasions. When NULL (default), the row position within each person (and day) is used.

lag

How many occasions back the predictors of the temporal network are, a whole number of at least 1: lag = 2 regresses each variable on every variable two occasions earlier (that lag only, not lags 1 and 2). Default 1.

standardize

Whether to grand-mean centre each variable and divide it by its pooled SD before the panel is augmented, as mlVAR::mlVAR(scale = TRUE) does. Default FALSE, matching mlVAR::mlVAR(scale = FALSE) (mlVAR's own default is TRUE); FALSE is the only setting for which agreement with mlVAR has been validated.

x

For the print() method: a net_mlvar.

...

For the print() and summary() methods: not used.

object

For the summary() method: a net_mlvar.

layer

For the plot() method: "temporal", "contemporaneous" or "between" to draw that network alone. Default NULL draws all three side by side.

Details

Estimation is done by idiographic::fit_mlvar(), called with estimator = "lmer", temporal = "fixed" and contemporaneous = "fixed". It follows mlVAR's lmer path:

  1. Drop rows with NA in id/day/beep and, with standardize = TRUE, grand-mean standardise each variable.

  2. Expand the per-(id, day) beep grid and right-join the original values, giving the augmented panel (augData).

  3. Add within-person lagged predictors (⁠L1_*⁠) and person-mean predictors (⁠PM_*⁠).

  4. For each outcome variable fit lmer(y ~ within + between-except-own-PM + (1 | id)) with REML = FALSE. Collect the fixed-effect temporal matrix B, the between-effect matrix Gamma, the random-intercept SDs (mu_SD) and the lmer residual SDs.

  5. Contemporaneous network: cor2pcor(D %*% cov2cor(cor(resid)) %*% D).

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

temporal

Directed network of the ⁠d x d⁠ matrix of fixed-effect lagged coefficients: the weight in row i, column j is the effect of variable i at t - lag on variable j at t, so edges run from predictor to outcome. Method "mlvar_temporal".

contemporaneous

Undirected ⁠d x d⁠ network of the partial correlations of the within-person lmer residuals. Method "mlvar_contemporaneous".

between

Undirected ⁠d x d⁠ network of the partial correlations of the person means, derived from D (I - Gamma). Method "mlvar_between".

coefficient table (attribute coefs)

The data frame coefs() returns: one row per ⁠(outcome, predictor)⁠ pair, with columns outcome, predictor, beta, se, t, p, ci_lower, ci_upper and significant.

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

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

build_network()

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 netobject or bare cograph_network built from sequences, or a tna model (whose stored states are decoded to their labels). Columns take the same roles as in build_network(): an id or a covariate is not a position, and the columns set aside are named in a message and kept as metadata. Association networks (cor, pcor, glasso, ising, mgm) hold variables, not sequences, and raise an error of class nestimate_bad_input, as do other fitted objects (an mcml, a group_tna, a netobject_group).

k

The number of subgroups (mixture components), a whole number of at least 2. Default 2.

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 50. On Unix the starts are screened in parallel on at most getOption("mc.cores", 2L) cores; the fit does not depend on the number of cores. A start whose EM stops with an error is left out with a warning of class nestimate_mmm_start_failed that counts them; when every start fails the error has class nestimate_mmm_failed.

max_iter

The most EM iterations a start may run, a positive whole number. Default 200.

tol

The convergence tolerance: EM stops when the log-likelihood changes by less than this between iterations (with covariate_effect = "em", also when its relative change does). A finite positive number; default 1e-6.

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

seed

An integer that makes the random starts reproducible. Default NULL. The session's own random stream is left as it was.

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 build_clusters(). For a netobject, names are looked up in its metadata first, so a typical call is build_mmm(net, k = 3, covariates = "session_label"). How they enter the model is set by covariate_effect. Default NULL.

covariate_effect

How covariates enter the model. "em" (default) makes the mixing proportions depend on them during EM, so they shape the subgroups found and add (k - 1) * p parameters for p covariate columns; rows with a missing covariate are dropped first, with a warning. "posthoc" fits a plain mixture on every sequence and relates the covariates to the subgroups only afterwards, with a multinomial logit, so neither their values nor their missingness change the subgroups. Ignored without covariates.

estimator

How the after-fit multinomial logit is estimated; it never affects the EM. "auto" (default) uses Firth's penalised likelihood (brglm2::brmultinom(), finite under separation) when a cell of the subgroup-by-covariate table has fewer than 5 sequences, and nnet::multinom() otherwise. "firth" and "multinom" force one of them ("multinom" warns about separation risk), and "chisq" runs descriptive tests instead of a logit. build_clusters() has the details. Ignored without covariates.

x

For the print() and plot() methods: a net_mmm fit, or the net_mmm_clustering attribute of the netobject_group built from one.

digits

For the print() methods: decimal places of the statistics. Default 3.

...

For the print(), summary() and plot() methods: not used; any extra argument raises an error.

object

For the summary() method: a net_mmm fit.

type

For the plot() methods: "posterior" (default), a histogram of each sequence's largest posterior probability, coloured by cluster; or "covariates", a forest plot of the covariate effects, for a model fitted with covariates. On a net_mmm_clustering, "predictors" is an alias of "covariates".

combined

For the plot() methods with type = "covariates": TRUE (default) draws the forest panels as one faceted plot; FALSE returns a list of ggplots, one per cluster.

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 $data slot, 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) * p for p covariate 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 netobject input, the network's threshold and scaling when they are not the defaults and its estimator settings in params, which build_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 of posterior, so session_ids can 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

compare_mmm, build_network

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 tna model (its integer states are decoded to their labels) or a netobject built from sequences (its states are read as stored). A data frame needs position columns named as a numbered run (T1, T2, ...); any other frame raises an error of class nestimate_bad_input that says to declare the roles in build_network() and pass the network. A missing value ends a run of observed states, so each run is its own trajectory, and trajectories with fewer than two states are dropped; with none left, build_mogen() stops. A one-hot network, an association network (cor, pcor, glasso, ising, mgm), a netobject_group and a 0/1 matrix raise an error of class nestimate_bad_input.

max_order

The highest order fitted, a whole number of at least 1; a value such as 2.7 is an error, not truncated. Default 5. A value at or above the length of the longest trajectory is lowered to that length minus 1, with a message.

criterion

How the order is selected: "aic" (default) or "bic" takes the order with the smallest criterion, and "lrt" uses the sequential likelihood-ratio tests described in Details, which select an order of at least 1.

lrt_alpha

The significance level of the likelihood-ratio tests, strictly between 0 and 1. Default 0.01. It only affects the selection with criterion = "lrt"; the p-values are computed under every criterion.

dof

How the parameters of each layer are counted. "paths" (default) counts every transition of the paths of length k that the observed first-order topology allows, as Scholtes (2017, Eq. 7) and pathpy do. "observed" counts only the transitions seen in the data (the rule before Nestimate 0.9.28); that count can fall as the order rises, and it under-penalises high orders on sparse data.

x

For the print() and plot() methods: a net_mogen object.

...

For the plot() method: further arguments passed to graphics::plot(). For the print() and summary() methods: ignored.

object

For the summary() method: a net_mogen object.

type

For the plot() method: "ic" (default) draws AIC and BIC against the order; "likelihood" draws the log-likelihood against the order. Both mark the selected order with a dashed line.

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_order after 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 (NA for 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_network weight 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 of transition_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_network edge data frame, with integer from and to node indices and a numeric weight; mogen_transitions() gives the readable table.

directed

Always TRUE.

n_nodes, n_edges

Counts for the graph of the selected order.

meta

The cograph_network metadata 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 (net_clustering, net_mmm), to build one network per cluster with the clustering's method. Per-cluster "latency" networks are not available (a clustering keeps the sequences, not the event times): name another method, or the error has class nestimate_latency_clusters.

method

The estimator. Each has its own page with its arguments:

Sequences and event logs
"relative" transition network analysis (TNA) see build_tna() for details
"frequency" frequency transition network analysis (FTNA) see build_ftna() for details
"attention" attention transition network analysis (ATNA) see build_atna() for details
"co_occurrence" co-occurrence network analysis (CNA) see build_cna() for details
"ngram" n-gram transition network analysis see build_ngram() for details
"gap" gap transition network analysis see build_gap() for details
"reverse" reverse (reply) transition network analysis see build_reverse() for details
Message logs
"latency" latency network analysis see build_latency() for details
One-hot codes
"wtna" window transition network analysis (WTNA) see build_wtna() for details
"wtna_cooccurrence" window co-occurrence network analysis see wtna() for details
Numeric variables
"cor" correlation network see build_cor() for details
"pcor" partial correlation network see build_pcor() for details
"glasso" EBIC graphical lasso network see build_glasso() for details
"ising" Ising model see build_ising() for details
"mgm" mixed graphical model (MGM) see build_mgm() for details

The other names list_estimators() shows ("tna", "ftna", "atna", "cna", ...) also work, and an estimator added with register_estimator() is called by its name. Required, except for a fitted clustering, whose own method is used.

...

The method's arguments, by name, as listed on its page, such as actor, action, start or lambda. For the print() and summary() methods: ignored.

group

A column to split the data by: one network per value, returned as a netobject_group. Default NULL.

scaling

Rescaling applied to the weights after estimation, in the order given: "minmax" rescales the weights to run from 0 to 1, over every cell for the transition methods (tna's rule, so with no zero cell the smallest weight becomes 0) and over the non-zero weights, into (0, 1], for the other methods, "max" divides by the largest absolute weight, "rank" replaces the non-zero weights by their ranks, and "normalize" makes each row's absolute weights sum to 1; an undirected network whose matrix it makes asymmetric becomes directed, so both of a pair's values are kept as edges. Zero weights stay zero under every option. Combine them as in c("rank", "minmax"). Default NULL (none).

threshold

Weights whose absolute value is below this are set to zero. Default 0 (none).

labels

New display labels for the nodes, applied after estimation: a two-column data frame (name, label), a named character vector c(name = "label") or a named list. It rewrites the node labels and the weight matrix's dimnames; nodes not listed keep their names. Default NULL.

inherit

Only when data is a fitted clustering (net_clustering or net_mmm) of a network: whether the per-cluster networks also take that network's threshold, scaling and estimator settings. FALSE (default) builds them with its method and the arguments given here; TRUE uses its settings for any not given here, when the clusters are built with its method. The relative networks of a net_mmm are the fitted chains, which take only its threshold and scaling.

x

For the print() methods: a netobject, netobject_group or netobject_ml, or the result of summary() on one.

n

For print() of a netobject: the number of edges listed, strongest first, self-loops included. Default 10; Inf lists them all, as does extract_edges() with include_self = TRUE; extract_transition_matrix() the weight matrix and extract_initial_probs() the initial probabilities.

digits

For print() of a netobject_group: decimal places of the weight range. Default 3.

object

For summary(): a netobject or netobject_group.

combined

For summary() of a netobject_group: TRUE (default) joins the groups' metrics into one data frame; FALSE returns a named list of the per-group tables.

format

For summary() of a netobject_group with combined = TRUE: "long" (default), one row per metric and group (metric, group, value), or "wide", one row per metric with a column per group. Both print as a metric-by-group grid.

i, j

For [ on a grouped summary: rows and columns, as for a data frame. A subset is a plain data frame.

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

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 mgm built 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, and tna metadata (cograph-compatible).

node_groups

Node groupings data frame, or NULL.

predictability

Named numeric vector of R-squared predictability values per node, for cor, pcor and glasso when predictability = 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 action set).

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). FALSE (default) adds none, TRUE adds one labelled "Start", and a single string adds one with that label. One-hot data, whose rows are time points rather than sequences, raises an error.

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 mark_terminal_state(), which fills all trailing missing cells with an absorbing state. FALSE (default), TRUE ("End") or a single string, as start.

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 or time_threshold; in one-hot data, each actor's rows. Default NULL.

action

The column holding each event's state; setting it declares the data an event log. Column names give no role: action, actor, time and session are read only when set. A column called Action with nothing declared raises an error of class nestimate_bad_input, and an undeclared time or session column beside action is named in a message of class nestimate_column_role. Default NULL.

time

The timestamp column of an event log. Events are ordered by it, and a gap longer than time_threshold starts a new sequence. Default NULL.

session

The column identifying sessions in an event log; each session is its own sequence, also without actor. Default NULL.

order

The column that orders events sharing a timestamp; without it, those events keep their row order. Default NULL.

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. FALSE turns the split off, so each actor (or actor-session) is one sequence. Default 900.

timezone

The Olson time zone for timestamps without an offset (passed to prepare()); timestamps with an offset, such as ...Z or +02:00, are converted from it. Default "UTC".

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, T1, T2, ..., or 1, 2, ...); numeric columns beside the run and character or factor columns outside it are then covariates. Any other frame, and columns of only 0 and 1, raise an error of class nestimate_bad_input: nothing says whether they are positions or one-hot codes. Default NULL.

metadata_cols

Columns to keep as the network's metadata (covariates), never as positions; they cannot overlap state_cols. A column left out of a numbered run of positions is named in a message of class nestimate_column_role, and listing it here or in state_cols settles it. Default NULL.

n_gram

The window length, a whole number of at least 2. Default 2.

group

A column to split the data by: one network per value, returned as a netobject_group. Default NULL.

scaling

Rescaling applied to the weights after estimation, in the order given: "minmax" rescales the weights to run from 0 to 1, over every cell for the transition methods (tna's rule, so with no zero cell the smallest weight becomes 0) and over the non-zero weights, into (0, 1], for the other methods, "max" divides by the largest absolute weight, "rank" replaces the non-zero weights by their ranks, and "normalize" makes each row's absolute weights sum to 1; an undirected network whose matrix it makes asymmetric becomes directed, so both of a pair's values are kept as edges. Zero weights stay zero under every option. Combine them as in c("rank", "minmax"). Default NULL (none).

threshold

Weights whose absolute value is below this are set to zero. Default 0 (none).

labels

New display labels for the nodes, applied after estimation: a two-column data frame (name, label), a named character vector c(name = "label") or a named list. It rewrites the node labels and the weight matrix's dimnames; nodes not listed keep their names. Default NULL.

params

Settings for the estimator, as a named list, as for build_tna(); also duration (one value per position, accumulated into times) or time_matrix (one row per sequence, one column per position), which measure the distance in time instead of positions. Default list().

...

Further arguments for build_network(): format ("auto", "wide", "long" or "onehot", to force a reading of data), and for event logs prepare()'s time options unix_time_unit, is_unix_time and custom_format. method cannot be given: each alias has its own (error of class nestimate_bad_input).

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 params (as in params = list(n = 250)). Non-numeric columns are set aside; a frame of two or more character or factor columns and fewer than two numeric ones is read as sequences and turned into per-row state counts first. A column named rid is set aside; columns with non-syntactic names, all-missing and constant columns, and rows with a missing value are dropped, each with a message; fewer than 2 variables or 3 complete rows raise an error.

actor

The id column naming whose observation each row is (a person). With level, the decomposition groups by it; without, it is set aside, not modelled. Default NULL.

level

Multilevel decomposition, with actor: "between" estimates the network of person means, "within" the network of deviations from them, and "both" returns the two as a netobject_ml. Default NULL (no decomposition).

...

Further arguments for build_network(). method cannot be given (error of class nestimate_bad_input).

cor_method

"pearson" (default), "spearman" or "kendall", passed to stats::cor().

predictability

Whether to compute each node's predictability (the R-squared of the node on its neighbours). It is stored on the network, and cograph::splot() draws it as a ring around each node. Default TRUE.

metadata_cols

Columns to keep as the network's metadata (covariates), never read as variables. Default NULL.

group

A column to split the data by: one network per value, returned as a netobject_group. Default NULL.

scaling

Rescaling applied to the weights after estimation, in the order given: "minmax" rescales the weights to run from 0 to 1, over every cell for the transition methods (tna's rule, so with no zero cell the smallest weight becomes 0) and over the non-zero weights, into (0, 1], for the other methods, "max" divides by the largest absolute weight, "rank" replaces the non-zero weights by their ranks, and "normalize" makes each row's absolute weights sum to 1; an undirected network whose matrix it makes asymmetric becomes directed, so both of a pair's values are kept as edges. Zero weights stay zero under every option. Combine them as in c("rank", "minmax"). Default NULL (none).

threshold

Weights whose absolute value is below this are set to zero. Default 0 (none).

labels

New display labels for the nodes, applied after estimation: a two-column data frame (name, label), a named character vector c(name = "label") or a named list. It rewrites the node labels and the weight matrix's dimnames; nodes not listed keep their names. Default NULL.

params

Settings for the estimator, as a named list, such as n, the sample size when data is a correlation or covariance matrix. The network stores them, so bootstrap_network() re-estimates with the same settings. Default list().

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 action set).

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). FALSE (default) adds none, TRUE adds one labelled "Start", and a single string adds one with that label. One-hot data, whose rows are time points rather than sequences, raises an error.

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 mark_terminal_state(), which fills all trailing missing cells with an absorbing state. FALSE (default), TRUE ("End") or a single string, as start.

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 or time_threshold; in one-hot data, each actor's rows. Default NULL.

action

The column holding each event's state; setting it declares the data an event log. Column names give no role: action, actor, time and session are read only when set. A column called Action with nothing declared raises an error of class nestimate_bad_input, and an undeclared time or session column beside action is named in a message of class nestimate_column_role. Default NULL.

time

The timestamp column of an event log. Events are ordered by it, and a gap longer than time_threshold starts a new sequence. Default NULL.

session

The column identifying sessions in an event log; each session is its own sequence, also without actor. Default NULL.

order

The column that orders events sharing a timestamp; without it, those events keep their row order. Default NULL.

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. FALSE turns the split off, so each actor (or actor-session) is one sequence. Default 900.

timezone

The Olson time zone for timestamps without an offset (passed to prepare()); timestamps with an offset, such as ...Z or +02:00, are converted from it. Default "UTC".

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, T1, T2, ..., or 1, 2, ...); numeric columns beside the run and character or factor columns outside it are then covariates. Any other frame, and columns of only 0 and 1, raise an error of class nestimate_bad_input: nothing says whether they are positions or one-hot codes. Default NULL.

metadata_cols

Columns to keep as the network's metadata (covariates), never as positions; they cannot overlap state_cols. A column left out of a numbered run of positions is named in a message of class nestimate_column_role, and listing it here or in state_cols settles it. Default NULL.

weighted

Whether each pair is weighted by one over the length of its sequence. Default FALSE.

group

A column to split the data by: one network per value, returned as a netobject_group. Default NULL.

scaling

Rescaling applied to the weights after estimation, in the order given: "minmax" rescales the weights to run from 0 to 1, over every cell for the transition methods (tna's rule, so with no zero cell the smallest weight becomes 0) and over the non-zero weights, into (0, 1], for the other methods, "max" divides by the largest absolute weight, "rank" replaces the non-zero weights by their ranks, and "normalize" makes each row's absolute weights sum to 1; an undirected network whose matrix it makes asymmetric becomes directed, so both of a pair's values are kept as edges. Zero weights stay zero under every option. Combine them as in c("rank", "minmax"). Default NULL (none).

threshold

Weights whose absolute value is below this are set to zero. Default 0 (none).

labels

New display labels for the nodes, applied after estimation: a two-column data frame (name, label), a named character vector c(name = "label") or a named list. It rewrites the node labels and the weight matrix's dimnames; nodes not listed keep their names. Default NULL.

params

Settings for the estimator, as a named list, as for build_tna(); also duration (one value per position, accumulated into times) or time_matrix (one row per sequence, one column per position), which measure the distance in time instead of positions. Default list().

...

Further arguments for build_network(): format ("auto", "wide", "long" or "onehot", to force a reading of data), and for event logs prepare()'s time options unix_time_unit, is_unix_time and custom_format. method cannot be given: each alias has its own (error of class nestimate_bad_input).

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:

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 tna model, a netobject or cograph_network, or a net_hon, net_hypa or net_mogen. With type = "vr", the matrix holds non-negative distances. The clique and Vietoris-Rips constructions read the weight matrix of any of these networks; with type = "pathway", a bare cograph_network or a matrix raises an error. For the print() and plot() methods: a simplicial_complex object.

type

The construction: "clique" (default), "pathway" or "vr" (alias "rips", stored as "vr").

threshold

For type = "clique": the smallest absolute edge weight an edge needs to enter (edges at exactly threshold are included). Zero weights are never edges. Default 0. Ignored for "vr", which uses max_scale, and for "pathway".

max_dim

The highest simplex dimension built (a k-simplex has k + 1 nodes), a non-negative whole number. Default 10. A larger clique is cut at this dimension and the complex is marked truncated; its top Betti number is then unreliable, and betti_numbers() warns with nestimate_truncated_complex. A pathway with more than max_dim + 1 distinct states is cut to its faces of that size, without the truncated mark.

max_pathways

For type = "pathway", how many pathways to keep: the most frequent higher-order paths for a net_hon, the most frequent transitions of mogen_transitions() at the optimal order for a net_mogen (the highest order fitted when the optimal one is 0), and for a net_hypa the anomalous paths ranked by their observed / expected ratio (see anomaly). Default NULL (all).

anomaly

For type = "pathway" on a net_hypa: which anomalous paths become simplices: "all" (default), "over" or "under". Over-represented and "all" paths are ranked by the largest ratio, under-represented ones by the smallest. Possible paths that never occur are left out, since a pathway simplex is a set of states observed together on a path.

max_scale

For type = "vr": the largest distance at which an edge enters; longer edges are left out. Default NULL, the largest finite distance.

...

For type = "pathway" on a tna model or netobject: method ("hon", the default, "hypa" or "mogen") chooses the higher-order model built from it, and the other arguments go to build_hon(), build_hypa() or build_mogen(). Other constructions ignore ... with a warning. For the print() and plot() methods: ignored.

combined

For the plot() method: TRUE (default) draws the four panels (f-vector, Betti numbers, simplicial degree per node and degree by dimension) as one 2 x 2 figure, which needs gridExtra; FALSE returns the four ggplots in a named list (f_vector, betti, degree, degree_heatmap) to print, save or arrange separately. A complex without edges (dimension 0) has no simplicial degree to draw and raises an error of class nestimate_bad_input.

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

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_simplices divided by the number of simplices a complete complex on n_nodes nodes would have up to dimension.

mean_dim

Mean simplex dimension.

type

"clique", "pathway" or "vr".

truncated

For the clique and Vietoris-Rips complexes: whether max_dim cut 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 action set), one-hot code columns (declared with codes), or a square matrix of transition counts or weights, which is row-normalised (every row needs a positive sum).

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). FALSE (default) adds none, TRUE adds one labelled "Start", and a single string adds one with that label. One-hot data, whose rows are time points rather than sequences, raises an error.

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 mark_terminal_state(), which fills all trailing missing cells with an absorbing state. FALSE (default), TRUE ("End") or a single string, as start.

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 or time_threshold; in one-hot data, each actor's rows. Default NULL.

action

The column holding each event's state; setting it declares the data an event log. Column names give no role: action, actor, time and session are read only when set. A column called Action with nothing declared raises an error of class nestimate_bad_input, and an undeclared time or session column beside action is named in a message of class nestimate_column_role. Default NULL.

time

The timestamp column of an event log. Events are ordered by it, and a gap longer than time_threshold starts a new sequence. Default NULL.

session

The column identifying sessions in an event log; each session is its own sequence, also without actor. Default NULL.

...

Further arguments for build_network(): format ("auto", "wide", "long" or "onehot", to force a reading of data), and for event logs prepare()'s time options unix_time_unit, is_unix_time and custom_format. method cannot be given: each alias has its own (error of class nestimate_bad_input).

order

The column that orders events sharing a timestamp; without it, those events keep their row order. Default NULL.

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. FALSE turns the split off, so each actor (or actor-session) is one sequence. Default 900.

timezone

The Olson time zone for timestamps without an offset (passed to prepare()); timestamps with an offset, such as ...Z or +02:00, are converted from it. Default "UTC".

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, T1, T2, ..., or 1, 2, ...); numeric columns beside the run and character or factor columns outside it are then covariates. Any other frame, and columns of only 0 and 1, raise an error of class nestimate_bad_input: nothing says whether they are positions or one-hot codes. Default NULL.

metadata_cols

Columns to keep as the network's metadata (covariates), never as positions; they cannot overlap state_cols. A column left out of a numbered run of positions is named in a message of class nestimate_column_role, and listing it here or in state_cols settles it. Default NULL.

codes

The one-hot code columns (one per state, 1 when the state is active); setting them declares one-hot data. Default NULL.

window_size

For one-hot data: how many consecutive rows form one window. Default 3. Windows on sequence data are set through params instead.

mode

For one-hot data: "non-overlapping" (default) or "overlapping" windows; build_wtna() describes how overlapping windows are counted.

group

A column to split the data by: one network per value, returned as a netobject_group. Default NULL.

scaling

Rescaling applied to the weights after estimation, in the order given: "minmax" rescales the weights to run from 0 to 1, over every cell for the transition methods (tna's rule, so with no zero cell the smallest weight becomes 0) and over the non-zero weights, into (0, 1], for the other methods, "max" divides by the largest absolute weight, "rank" replaces the non-zero weights by their ranks, and "normalize" makes each row's absolute weights sum to 1; an undirected network whose matrix it makes asymmetric becomes directed, so both of a pair's values are kept as edges. Zero weights stay zero under every option. Combine them as in c("rank", "minmax"). Default NULL (none).

threshold

Weights whose absolute value is below this are set to zero. Default 0 (none).

labels

New display labels for the nodes, applied after estimation: a two-column data frame (name, label), a named character vector c(name = "label") or a named list. It rewrites the node labels and the weight matrix's dimnames; nodes not listed keep their names. Default NULL.

params

Settings for the estimator, as a named list. Transitions are counted with tna's weighted and concat options, and window_size (with window_span, or windowed = TRUE for a size of 2) counts them between consecutive non-overlapping blocks of that many positions, as tna::tna() does; mode = "overlapping" then raises a warning of class nestimate_ignored_mode. The network keeps these settings, and the resampling verbs such as bootstrap_network() re-estimate with them. Default list().

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 NULL: every column outside the other roles.

window_size

How many consecutive rows form one window. Default 3.

mode

"non-overlapping" (default) or "overlapping" windows: overlapping ones slide by one row, as tna::import_onehot(window_type = "sliding"), and are counted in blocks of window_size.

type

"frequency" (default) keeps the counts; "relative" divides each row by its sum.

actor

The column naming who each row belongs to; windows do not cross actors. Default NULL.

session

The column identifying sessions; windows do not cross sessions. Default NULL.

metadata_cols

Columns to keep as the network's metadata, never read as codes. Default NULL.

group

A column to split the data by: one network per value, returned as a netobject_group. Default NULL.

scaling

Rescaling applied to the weights after estimation, in the order given: "minmax" rescales the weights to run from 0 to 1, over every cell for the transition methods (tna's rule, so with no zero cell the smallest weight becomes 0) and over the non-zero weights, into (0, 1], for the other methods, "max" divides by the largest absolute weight, "rank" replaces the non-zero weights by their ranks, and "normalize" makes each row's absolute weights sum to 1; an undirected network whose matrix it makes asymmetric becomes directed, so both of a pair's values are kept as edges. Zero weights stay zero under every option. Combine them as in c("rank", "minmax"). Default NULL (none).

threshold

Weights whose absolute value is below this are set to zero. Default 0 (none).

labels

New display labels for the nodes, applied after estimation: a two-column data frame (name, label), a named character vector c(name = "label") or a named list. It rewrites the node labels and the weight matrix's dimnames; nodes not listed keep their names. Default NULL.

params

Settings for the estimator, as a named list. The network keeps them. Default list().

...

Further arguments for build_network(). method cannot be given (error of class nestimate_bad_input).

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 netobject or cograph_network that carries its data, or a netobject_group or mcml, whose networks (for an mcml, the macro network and each cluster's) are assessed one by one. A tna model or a group_tna (package tna) is first rebuilt as a network from its own sequences (see as_netobject()). A network without data raises an error, and one that rests on a single sequence, or one-hot data with no actor or session, has no cases to drop and raises an error of class nestimate_single_sequence. A network built with method = "latency" raises an error of class nestimate_latency_resampling: latency networks are not resampled. For the print() and plot() methods: the result of casedrop_reliability() (for print(), also the summary() of a group result).

iter

The number of random subsets drawn for each drop proportion, at least 2. Default 1000.

drop_prop

The proportions of cases to drop, each strictly between 0 and 1, in any order. Default seq(0.1, 0.9, by = 0.1). A proportion that drops no case of a small sample (n * p < 1) is not run (its metrics are NA) and counts as not passing, with a warning of class nestimate_drop_prop_skipped. For the summary() method of a group result: the one proportion to report, which must be one of those the result was built with; a value outside them raises an error listing the available ones. Default NULL there, the middle proportion of the grid (the lower of the two middle ones for an even number).

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

certainty

The share of iterations that must reach threshold for a drop proportion to pass, between 0 and 1. Default 0.95. It is the share of all iterations: one in which the correlation is undefined (the edge vector is constant in that subset), or in which the network could not be re-estimated, counts as not reaching threshold.

method

The correlation: "spearman" (default) compares ranks, so it is not affected by the scale of the weights, which often span several orders of magnitude; "pearson" compares the weight magnitudes; "kendall" is Kendall's tau.

include_diag

Whether self-loops are part of the edge vector. Default FALSE.

seed

A number that makes the subsets reproducible. The session's own random stream is left as it was. For a netobject_group or mcml, each network is assessed from the same seed. Default NULL.

target

The cells compared. "existing" compares only the cells that are non-zero in the original network; "all" compares every cell, zeros included, so edges that appear once cases are dropped count. "auto" (default) uses "existing" for unscaled and unthresholded transition networks, where an absent transition cannot appear in a subset, and "all" otherwise. include_diag applies to either.

actor

The column identifying the actor each sequence belongs to (for example "student_id" for sessions nested in students), looked up in the network's metadata or its wide sequence data, as in bootstrap_network(). With it, whole actors are dropped; see Nested data and actor. Several column names, outermost first, are nested levels, of which the outermost is dropped. Default NULL: sequences are dropped one by one. Available for transition networks (relative, frequency, co-occurrence).

digits

For the print() method of a single result: the decimal places of the metric table. Default 3.

...

For the print(), summary() and plot() methods: ignored.

object

For the summary() methods: the result of casedrop_reliability().

combined

For the plot() method of a single result: TRUE (default) draws the four metrics as panels of one plot; FALSE returns a named list of four single-panel plots, one per metric.

metric

For the plot() method of a group result: the metric drawn, "correlation" (default), "mean_abs_dev", "median_abs_dev" or "max_abs_dev".

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:

cs

The CS-coefficient: the largest drop proportion at which the correlation reaches threshold in at least certainty of the iterations. 0 when no proportion passes; NA when the original edge weights do not vary (constant up to rounding error, relative to their size), so the correlation is undefined.

summary

A data frame with one row per metric and drop proportion: metric ("mean_abs_dev", "median_abs_dev", "correlation", "max_abs_dev"), drop_prop, and the mean, sd, median, mad, q025 and q975 of the metric over the iterations.

metrics

The per-iteration values: a named list of four matrices, one per metric, with one row per iteration and one column per drop proportion.

correlations

The same matrix as the correlation entry of metrics.

drop_prop, threshold, certainty, iter, method, include_diag

The settings used.

n_cases

The number of cases resampled from: sequences for a transition network (actors with actor), rows of the data otherwise.

actor

With actor only: the actor column(s).

n_edges

The number of cells compared, set by target and include_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 netobject from build_network(), a bare cograph_network (converted to one), or a netobject_group or mcml, each of whose networks is assessed. A tna model or a group_tna (package tna) is first rebuilt as a network from its own sequences (see as_netobject()). Any other object, or a network built without its data, raises an error. For the print() methods: a net_stability or net_stability_group; for the plot() method: a net_stability.

measures

The centrality measures to assess. The default is "InStrength", "OutStrength" and "Betweenness"; NULL takes net_centrality()'s default ("InStrength", "Betweenness", "Diffusion"), and "all" every built-in measure: "OutStrength", "InStrength", "ClosenessIn", "ClosenessOut", "Closeness", "Betweenness", "BetweennessRSP", "Diffusion" and "Clustering" (net_centrality() defines them). "InCloseness" and "OutCloseness" are accepted for "ClosenessIn" and "ClosenessOut". Other names need centrality_fn; without it they raise an error.

iter

The number of random subsets drawn at each drop proportion, at least 2. Default 1000.

drop_prop

The proportions of cases to drop, each strictly between 0 and 1. Default seq(0.1, 0.9, by = 0.1). A proportion that would leave fewer than 2 cases is skipped and counts as not reaching threshold. The CS-coefficient is the largest proportion that meets certainty, in whatever order they are given.

threshold

The correlation with the full network's centralities that a draw must reach, between 0 and 1. Default 0.7.

certainty

The share of draws at a drop proportion that must reach threshold, between 0 and 1. Default 0.95. It is a share of all draws: one with an undefined correlation counts as not reaching threshold.

method

The correlation between the full and the subset centralities: "pearson" (default), "spearman" or "kendall".

centrality_fn

A function of your own that takes the weight matrix and returns a named list of centrality vectors, such as list(my_metric = ...). It is called as centrality_fn(mat) and used only for the requested measures that are not built-in; list their names in measures. Default NULL.

loops

Whether self-loops (staying in a state) count. With FALSE (default) they are left out of every measure; the stored matrix is not changed.

normalize

Whether to range-normalise every measure to 0–1, as tna::centralities(normalize = TRUE) does. Default FALSE.

invert

Whether a heavier edge is a shorter step in the shortest-path measures (distance = 1 / weight), as in tna. Default TRUE; with FALSE the weight is the distance. It affects betweenness and closeness only, not "BetweennessRSP".

normalize_diffusion

Whether to range-normalise Diffusion even when normalize = FALSE. Default TRUE.

seed

An integer that makes the random subsets reproducible. Default NULL. The session's own random stream is left as it was; a group's networks are each started from the same seed.

actor

The column identifying the actor each sequence belongs to (for example "student_id" for sessions nested in students), looked up in the network's metadata or its wide sequence data, as in bootstrap_network(). With it, whole actors are dropped; see Nested data and actor. Several column names, outermost first, are nested levels, of which the outermost is dropped. Default NULL: sequences are dropped one by one. Available for transition networks (relative, frequency, co-occurrence).

...

For the print(), summary() and plot() methods: not used.

object

For the summary() methods: a net_stability or net_stability_group.

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 iter x length(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 actor only: 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 netobject built with build_network() using method = "relative" (or its aliases "tna", "transition"), without scaling, or a netobject_group of such networks, each handled on its own. A bare cograph_network is recounted from the sequences it carries, and used only when they reproduce its weights; otherwise, and for an mcml, an error of class nestimate_bad_input is raised. A tna model or a group_tna (package tna) is first rebuilt as a network from its own sequences (see as_netobject()). Another method or a scaled network raises an error. For the print() method: a net_certainty object.

prior

The Dirichlet concentration added to every cell of the count matrix, zero cells and self-loops included; a positive number. Default 0.5, the Jeffreys prior.

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 p_value column) is below it. Default 0.05, a 95% interval. Named to match bootstrap_network().

inference

The decision rule. "stability" (default) takes the posterior mass outside the band consistency_range times the edge's weight; "threshold" takes the posterior mass below edge_threshold.

consistency_range

For inference = "stability": the two multiplicative bounds of the band around each weight, positive numbers in either order. Default c(0.75, 1.25).

edge_threshold

For inference = "threshold": the weight an edge must exceed. Default NULL: the 10th percentile of the non-zero weights. Ignored for "stability".

...

For the print() method: ignored.

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 netobject, bare cograph_network or tna model with transition weights, a numeric transition matrix, or a wide sequence data frame or character matrix (estimated with build_network(method = "relative")). A netobject_group is analysed network by network. An association network (cor, pcor, glasso, ising, mgm) or a matrix with negative entries raises an error of class nestimate_not_markov. For the print() and plot() methods: a chain_structure object (print() also takes a chain_structure_group or a summary_chain_structure).

normalize

Whether to rescale rows that do not sum to 1 so that they do, with a warning, as passage_time() does. Default TRUE. With FALSE, such a matrix raises an error. A state with no outgoing transitions (a row of zeros) raises an error either way.

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. tol is also the tolerance of the reversibility check (detailed balance). Default 1e-10. It does not govern the absorbing-state test: a state is absorbing only when P[i, i] equals 1 to within a fixed tolerance of about 1.5e-8, so raising tol to ignore tiny transition probabilities never reclassifies a near-deterministic state as absorbing.

...

Ignored, except by the print() methods of a chain_structure_group, which pass it to each network's print(), and of a summary_chain_structure, which pass it to print.data.frame().

show_values

For the plot() method: whether to print each cell's probability inside it. Default TRUE. Values are never printed for more than 20 states; set FALSE earlier when the labels overlap (from about 10 states).

digits

For the plot() method: decimal places of the cell values. Default 2.

object

For the summary() methods: a chain_structure or chain_structure_group object.

table

For summary(): "states" (default), one row per state, or "absorption", one row per transient state and closed class.

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:

states

Character vector of state names.

classification

Named character vector, one of "absorbing", "recurrent" or "transient" per state.

communicating_classes

List of state-name vectors, one per strongly connected component of the support graph.

recurrent_classes

The communicating classes that are closed (no transition leaves the class).

transient_classes

The communicating classes that are not closed.

absorbing_states

Character vector of states with P[i, i] equal to 1, to within about 1.5e-8; tol does not relax this.

period

Named integer vector: the period of each recurrent state, NA for transient states.

is_irreducible

TRUE when there is exactly one communicating class.

is_aperiodic

TRUE when every recurrent state has period 1.

is_regular

is_irreducible && is_aperiodic.

is_reversible

TRUE when the chain satisfies detailed balance against its stationary distribution; NA for a chain that is not irreducible (no unique stationary distribution).

hitting_probabilities

⁠n x n⁠ matrix whose ⁠[i, j]⁠ entry is the probability of ever reaching j from i, computed over the same tol-thresholded support graph as classification, 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_probabilities

⁠n_transient x n_closed⁠ matrix whose ⁠[i, j]⁠ entry is the probability that the chain started in transient state i ends in closed class j; 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 example B+C). NULL when the chain has no transient state.

mean_absorption_time

Named numeric vector of the expected number of steps each transient state takes to enter a closed class, whichever it is. NULL when absorption_probabilities is.

P

The 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:

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 build_hypergraph() or bipartite_groups().

weighted

Whether to use the hypergraph's incidence values. With TRUE (default), a weighted hypergraph (from bipartite_groups() with weight) gives a weighted projection; with FALSE, the incidence is binarised first, so each weight counts the hyperedges the pair shares. For an unweighted hypergraph the two agree.

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 build_clusters() unchanged: any input it takes, such as a wide data frame of sequences or a network built from sequences.

k

The cluster counts to try. Default 2:5. Each must be a whole finite number, or an error is raised; build_clusters() also requires each to be at least 2 and at most the number of sequences minus 1.

dissimilarity

The dissimilarity measures to try. Default "hamming". "all" expands to every supported measure: "hamming", "osa", "lv", "dl", "lcs", "qgram", "cosine", "jaccard" and "jw", and may stand beside named ones (each is fitted once).

method

The clustering algorithms to try. Default "ward.D2" (where build_clusters() defaults to "pam"). "all" expands to every supported algorithm: "pam", "ward.D2", "ward.D", "complete", "average", "single", "mcquitty", "median" and "centroid".

...

Further arguments of build_clusters(), used for every combination: weighted, lambda, q, p, seed, na_syms, covariates and estimator; any other name raises an error. weighted = TRUE works only with dissimilarity = "hamming" and is refused before any fit when the sweep holds another measure. The print(), summary() and plot() methods take no further arguments and raise an error on any.

x

For the print() and plot() methods: a cluster_choice.

digits

For the print() method: the decimal places of the silhouette, within-cluster distance and size ratio. Default 3. Must be a single non-negative whole number.

object

For the summary() method: a cluster_choice.

type

For the plot() method: the kind of plot, one of "auto" (default), "lines", "bars", "heatmap", "tradeoff" and "facet" (see Plot types). A type the sweep cannot support raises an error that names the alternatives, and so does a table with a single configuration, which has nothing to compare.

abbrev

For the plot() method: whether to shorten the dissimilarity and method names (e.g. "hamming" to "ham", "ward.D2" to "wD2") on the axes, point labels and legend. Default FALSE.

combined

For plot(type = "facet"): TRUE (default) draws one panel per method in a single plot; FALSE returns a named list of one-method plots instead. Ignored by the other types, but must still be a single logical value.

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() (from cluster::pam() for "pam", with cluster::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 only dissimilarity or only method is 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_dist is drawn as a second line on the same axis. With all three swept, the lines follow dissimilarity and 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 dissimilarity and method, 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 build_clusters().

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 net_clustering, a net_mmm, a netobject_group carrying a clustering (built by cluster_network() or by build_network() from a net_clustering or net_mmm), or a net_mmm_clustering. A netobject_group without a clustering, and any other object, raise an error. For the print() and plot() methods: a net_cluster_diagnostics.

...

Not used: an extra argument raises an error, here and in the print() and summary() methods. For plot(): further arguments for the clustering's own plot() method, such as combined.

digits

For print(): decimal places of the silhouette widths, distances, AvePP, entropy and information criteria, a non-negative whole number. Default 3. Percentages are always shown to one decimal.

type

For plot(): the view, passed to the clustering's own plot() method. Default NULL, which draws "silhouette" for a distance clustering and "posterior" for a mixture. A distance clustering also takes "mds", "heatmap" and "predictors" (see build_clusters()); a mixture takes "covariates", with "predictors" accepted for it when the source is a net_mmm_clustering (see build_mmm()).

object

For the summary() method: a net_cluster_diagnostics.

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_pct and class_err_pct are in percent.

overall

List of the family's summary measures: silhouette for distance; avepp_overall, entropy and classification_error (a proportion) for a mixture.

ics

For a mixture, a list with BIC, AIC, ICL and log_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 netobject or bare cograph_network built from sequences, or a tna model (whose stored states are decoded to their labels). Columns take the same roles as in build_network(): an id or a covariate is not a position, and the columns set aside are named in a message and kept as metadata. Association networks (cor, pcor, glasso, ising, mgm) hold variables, not sequences, and raise an error of class nestimate_bad_input, as do other fitted objects (an mcml, a group_tna, a netobject_group).

k

The number of subgroups (mixture components), a whole number of at least 2. Default 2.

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 50. On Unix the starts are screened in parallel on at most getOption("mc.cores", 2L) cores; the fit does not depend on the number of cores. A start whose EM stops with an error is left out with a warning of class nestimate_mmm_start_failed that counts them; when every start fails the error has class nestimate_mmm_failed.

max_iter

The most EM iterations a start may run, a positive whole number. Default 200.

tol

The convergence tolerance: EM stops when the log-likelihood changes by less than this between iterations (with covariate_effect = "em", also when its relative change does). A finite positive number; default 1e-6.

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

seed

An integer that makes the random starts reproducible. Default NULL. The session's own random stream is left as it was.

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 build_clusters(). For a netobject, names are looked up in its metadata first, so a typical call is build_mmm(net, k = 3, covariates = "session_label"). How they enter the model is set by covariate_effect. Default NULL.

covariate_effect

How covariates enter the model. "em" (default) makes the mixing proportions depend on them during EM, so they shape the subgroups found and add (k - 1) * p parameters for p covariate columns; rows with a missing covariate are dropped first, with a warning. "posthoc" fits a plain mixture on every sequence and relates the covariates to the subgroups only afterwards, with a multinomial logit, so neither their values nor their missingness change the subgroups. Ignored without covariates.

estimator

How the after-fit multinomial logit is estimated; it never affects the EM. "auto" (default) uses Firth's penalised likelihood (brglm2::brmultinom(), finite under separation) when a cell of the subgroup-by-covariate table has fewer than 5 sequences, and nnet::multinom() otherwise. "firth" and "multinom" force one of them ("multinom" warns about separation risk), and "chisq" runs descriptive tests instead of a logit. build_clusters() has the details. Ignored without covariates.

cluster_by

The clustering family. Only "mmm" (the default) is accepted; it is there so cluster_mmm() and cluster_network() share one call shape. Any other value raises an error that points to cluster_network().

...

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, netobject, bare cograph_network or tna model, as accepted by build_clusters() (or by build_mmm() when cluster_by = "mmm"). A wtna network is accepted only with cluster_by = "mmm"; dissimilarity clustering refuses it with an error of class nestimate_bad_input.

k

The number of clusters, a whole number from 2 to one less than the number of sequences. Required.

cluster_by

The clustering algorithm. "pam" (default) and the hierarchical methods "ward.D2", "ward.D", "complete", "average", "single", "mcquitty", "median" and "centroid" are passed to build_clusters() as its method; "mmm" fits a mixed Markov model with build_mmm() instead.

dissimilarity

The distance between sequences, as in build_clusters(). Default "hamming". Giving it with cluster_by = "mmm" raises an error.

inherit

When data is a netobject, whether the per-cluster networks take its threshold, scaling and estimator settings (⁠$params⁠: start and end states, an attention network's lambda, an n-gram's n_gram). FALSE (default) builds them afresh with the network's method and the arguments given in the call; TRUE uses the network's settings for any not given in the call, when the clusters are built with its method. Under cluster_by = "mmm" the relative networks are the fitted chains, which take only its threshold and scaling.

...

Arguments for the two stages, routed by name. For dissimilarity clustering, build_clusters()'s na_syms, weighted, lambda, seed, q, p, covariates and estimator go to the clustering; with cluster_by = "mmm", build_mmm()'s n_starts, max_iter, tol, smooth, seed, covariates, covariate_effect and estimator go to the mixture fit. Everything else is meant for the network stage and must be an argument of build_network() or of a registered estimator; any other name raises an error before either stage runs. A name both stages accept goes to the clustering: under dissimilarity clustering a lambda given here is the Hamming decay of the clustering and never reaches an attention network, and the same holds for weighted. When data is a netobject, the arguments that read its data are reused for the per-cluster networks, and a value given in the call replaces the stored one. The Details section lists which network arguments take effect.

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 netobject from build_network() or a bare cograph_network, whose weight matrix is used; or a tna model, whose weights are used. An mcml object is returned unchanged. A matrix without names labels its nodes "1", "2", ....

clusters

The cluster of each node, required (NULL, the default, raises an error; build_mcml() is the verb that reads clusters from a netobject's node table). Accepted forms:

membership vector

One value per node, in the order of the matrix rows, such as c(1, 1, 2, 2, 3, 3) or c("A", "A", "B"). A named vector is matched to the nodes by name instead. Numeric values give clusters in sorted order, character values in order of first appearance.

data frame

Node names in the first column, cluster names in the second, such as data.frame(node = c("A", "B", "C"), group = c("G1", "G1", "G2")); the clusters come in alphabetical order.

named list

Cluster names mapped to their nodes, such as list(Alpha = c("A", "B"), Beta = c("C", "D")); the clusters keep the list's order.

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 net_aggregate_weights(); zero edges are left out first.

"sum"

(default) The total weight, which keeps the total flow. Suits counts such as transition frequencies.

"mean"

The mean weight, so a cluster of 5 nodes does not get 5 times the weight of a cluster of 1. Suits a matrix of probabilities (rows summing to 1), where a sum would grow with cluster size.

"median"

The median weight, less affected by a few extreme weights.

"max"

The strongest connection.

"min"

The weakest connection.

"density"

The total weight divided by the number of possible edges between the two clusters (n_i * n_j). It equals "mean" when the block has no zero edges and is smaller than it when it has some.

"geomean"

The geometric mean of the positive weights, for multiplicative processes.

directed

Whether the network is directed, so that A->B and B->A are separate edges. Default TRUE. FALSE replaces the matrix by the mean of it and its transpose before aggregating, which makes every layer symmetric; each undirected edge then counts once, so a cluster's macro self-loop aggregates the upper triangle of its block with the diagonal (and "density" divides by its n_i (n_i + 1) / 2 possible edges).

compute_within

Whether to build the within-cluster networks, one n_i x n_i matrix per cluster. Default TRUE; FALSE skips them when only the macro network is needed, and summary() then reports their totals as NA.

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; and data, NULL on this route.

clusters

A named list of one mcml_layer per cluster: the n_i x n_i submatrix of its nodes, self-loops included, and its normalised column sums as inits (1 for a single-node cluster). NULL when compute_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 of build_mcml() fill it.

meta

A list with type (always "aggregate" here), method, directed, n_nodes, n_clusters, cluster_sizes (a named integer vector) and source ("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 net_mlvar from build_mlvar() has a method, and any other object raises an error.

...

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 build_mmm() accepts: a wide data frame, a netobject or cograph_network built from sequences, or a tna model.

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 2:5.

return_fits

Whether to keep the fitted models. With TRUE, the net_mmm fits are attached to the result as its "fits" attribute, a list named by k, so the chosen model needs no second run of the EM. Default FALSE, which returns only the comparison table.

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 50. On Unix the starts are screened in parallel on at most getOption("mc.cores", 2L) cores; the fit does not depend on the number of cores. A start whose EM stops with an error is left out with a warning of class nestimate_mmm_start_failed that counts them; when every start fails the error has class nestimate_mmm_failed.

max_iter

The most EM iterations a start may run, a positive whole number. Default 200.

tol

The convergence tolerance: EM stops when the log-likelihood changes by less than this between iterations (with covariate_effect = "em", also when its relative change does). A finite positive number; default 1e-6.

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

seed

A seed for reproducible starts, applied afresh to each fit (every k starts from the same random state). Default NULL.

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 build_clusters(). For a netobject, names are looked up in its metadata first, so a typical call is build_mmm(net, k = 3, covariates = "session_label"). How they enter the model is set by covariate_effect. Default NULL.

covariate_effect

How covariates enter the model. "em" (default) makes the mixing proportions depend on them during EM, so they shape the subgroups found and add (k - 1) * p parameters for p covariate columns; rows with a missing covariate are dropped first, with a warning. "posthoc" fits a plain mixture on every sequence and relates the covariates to the subgroups only afterwards, with a multinomial logit, so neither their values nor their missingness change the subgroups. Ignored without covariates.

estimator

How the after-fit multinomial logit is estimated; it never affects the EM. "auto" (default) uses Firth's penalised likelihood (brglm2::brmultinom(), finite under separation) when a cell of the subgroup-by-covariate table has fewer than 5 sequences, and nnet::multinom() otherwise. "firth" and "multinom" force one of them ("multinom" warns about separation risk), and "chisq" runs descriptive tests instead of a logit. build_clusters() has the details. Ignored without covariates.

x

For the print() and plot() methods: an mmm_compare table.

...

For the print(), summary() and plot() methods: not used; any extra argument raises an error.

object

For the summary() method: an mmm_compare table.

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

build_mmm(), cluster_mmm()

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 netobject, a cograph_network or a numeric square matrix, or a netobject_group whose members i and j are compared. A tna model or a group_tna (package tna) is first rebuilt as a network from its own sequences (see as_netobject()). For the print() and plot() methods: a net_comparison object.

...

Not used.

y

The second network, in the same forms (not used for a netobject_group). The two must hold the same nodes and have no missing weights. Named inputs are aligned by node name, so the node order may differ; different node sets, or missing, empty or duplicated names, raise an error. A matrix without names is matched to the other input by position and takes its node names; when neither input has names the nodes are labelled V1, V2, ....

scaling

The scaling applied to each weight matrix before comparison. Default "none". One of:

"none"

The weights as they are.

"minmax"

(w - \min) / (\max - \min), which maps them to [0, 1]; a constant matrix is left as it is.

"max"

w / \max|w|, dividing by the largest absolute weight, so signs are kept; a matrix of zeros is left as it is.

"rank"

Average ranks, mapped to [0, 1] by min-max; an ordinal scaling. A constant matrix keeps its (equal) ranks.

"zscore"

(w - \bar w) / s_w, the standard score; a constant matrix is only centred.

"robust"

(w - \mathrm{med}(w)) / \mathrm{mad}(w), a standard score from the median and the median absolute deviation, less affected by outliers; with a MAD of 0 the weights are only centred.

"log"

\log(w); needs w > 0: a weight at or below 0 raises an error of class nestimate_bad_input (use "log1p" for networks with zeros).

"log1p"

\log(1 + w); defined for w > -1: a weight of -1 or below raises an error of class nestimate_bad_input.

"softmax"

A numerically stable softmax over all the cells.

"quantile"

The empirical cumulative distribution of the cells.

"frobenius"

The matrix divided by its Frobenius norm \|W\|_F = \sqrt{\sum w_{ij}^2}, a matrix-level normalisation.

"row"

Each row divided by the sum of its absolute values, so the rows sum to 1 for non-negative weights; rows summing to zero are left unchanged.

Scalings that produce negative weights ("zscore", "robust") work with network = TRUE: the side-by-side distances are computed on the absolute weights.

measures

Centrality measures to compare. Default character(0) (none). Any built-in measure of net_centrality() can be named: "OutStrength", "InStrength", "ClosenessIn", "ClosenessOut", "Closeness", "Betweenness", "BetweennessRSP", "Diffusion" and "Clustering" ("InCloseness" and "OutCloseness" are accepted for "ClosenessIn" and "ClosenessOut"). Unknown names are dropped with a warning. The centralities are computed on the scaled matrices as directed networks, without self-loops.

network

Whether to add the two networks' metrics side by side (the metrics summary() reports for a netobject). Default TRUE.

i, j

For a netobject_group: the two members to compare, by index or name. Defaults 1 and 2; the two must differ, and a member that does not exist raises an error.

type

For plot(): the view. "scatter" (default) plots each cell's weight in y against its weight in x, with the line of perfect agreement (dashed), an OLS fit with its 95% band and the Pearson, Spearman and Kendall correlations. "heatmap" draws the difference matrix x - y on the diverging palette: blue where x is larger, red where y is larger, white where they agree. "diff_hist" is a histogram of the absolute differences ⁠|x - y|⁠, with a density curve, a rug of the cells and lines at the mean and median. "weight_dist" overlays the distributions of ⁠|x|⁠ and ⁠|y|⁠. "all" draws these four views in a 2 x 2 grid.

combined

For plot() with type = "all": TRUE (default) arranges the four views into one 2 x 2 gtable, which needs the gridExtra package; FALSE returns them as a named list of ggplots, to print, save or lay out separately. Ignored for the other views.

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, x and y, aligned by node.

difference_matrix

The scaled x minus the scaled y.

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, NA where a weight is -1 or below), standardised weights and their ratio. A ratio is NA where its denominator is zero, and the standardised weights are NA when a matrix is constant.

summary_metrics

A data frame of the 22 agreement measures, with columns category, metric and value.

network_metrics

When network = TRUE: a data frame with columns metric, x and y, one row per network metric.

centrality_differences, centrality_correlations

When measures is 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 netobject, netobject_group (its members are compared individually and keep their names), cograph_network, psychnet, mcml, tna, group_tna, square numeric matrices, or one unnamed list of these. Name the arguments to name the networks, as in ⁠early = a, late = b⁠; an unnamed network is named after its method. Any other input raises an error. For the plot() method: passed to cograph::splot() in the "networks" and "difference" views (such as layout, node_size or minimum) and ignored by the other views; the print() method ignores it.

reference

The network every other one is compared against, by name or index; it is always network_a of its pairs, so diff = reference - other. Default NULL, which compares all pairs. A name or index that matches no network raises an error of class nestimate_compare_reference_unknown.

scaling

A rescaling applied to every weight matrix before the comparison. "none" (default) keeps the weights as estimated; "minmax", "max", "rank", "zscore", "robust" (median and MAD), "log", "log1p", "softmax" and "quantile" (empirical percentile) transform all cells of a matrix together; "frobenius" divides by the Frobenius norm and "row" makes each row's absolute weights sum to 1. "log" needs strictly positive weights and "log1p" weights of at least -1, otherwise an error of class nestimate_compare_scaling_domain is raised. The tests are defined on the networks as estimated, so any other value than "none" with test raises an error of class nestimate_compare_scaling_inference.

measures

The centrality measures compared in the node table. Default c("InStrength", "OutStrength", "Betweenness"). Any of "OutStrength", "InStrength", "ClosenessIn", "ClosenessOut", "Closeness", "Betweenness", "BetweennessRSP", "Diffusion" and "Clustering", or "all" for these nine (see net_centrality()). NULL or character(0) skips the node table. Unknown names are dropped with a warning of class nestimate_compare_unknown_measure.

labels

Names for the networks, one per network after groups are expanded; they replace the argument names. Default NULL. A vector of the wrong length raises an error of class nestimate_compare_labels_length. For the plot() method: whether to print the signed difference on the edge and node views and the p-values on the inference view. Default TRUE; the heatmap always prints its values.

test

The inference to add, one or more of "none" (default), "permutation", "bayes" and "bootstrap". Each fills the columns it supports (see Details). The permutation and Bayesian tests need networks that carry their data and share one estimation method, and the Bayesian test needs "relative" or "frequency" networks; otherwise the call raises nestimate_compare_test_unsupported. The permutation and bootstrap tests raise nestimate_latency_resampling on a latency network.

iter

The number of permutations, posterior draws or bootstrap replicates per pair, at least 2. Default 1000.

alpha

The significance level of the permutation and bootstrap tests, a number between 0 and 1; the Bayesian credible interval covers 1 - alpha. Default 0.05.

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 permutation() does. Default "none".

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 actor (an error of class nestimate_bad_actor). Default FALSE.

rope

The half-width of a region of practical equivalence on the difference scale, for the Bayesian test. It adds bayes_p_rope and a bayes_decision of "different", "equivalent" or "undecided" to the edge table. Default NULL (none).

seed

An integer that makes the tests reproducible. It is passed unchanged to the test of every pair, so test = "permutation" gives the p-values of permutation() called with the same seed, and likewise for bayes_compare() and vertex_compare(). Default NULL.

actor

The column identifying the actor each sequence belongs to (such as "student_id" when sessions are nested in students, or "Group" for students nested in teams). It is passed to permutation(), which then shuffles whole actors; see its sections Nested data and actor and ICC and design effect. The ICC and design effects are added to the global table under the category "Nesting". Set it when the networks come from groups made of different actors (each student in one group): shuffling single sequences is then too liberal. When the groups vary within the same actors (pre- and post-test sessions of the same students), actor shuffles within each actor and the plain test is also valid; see Nested data and actor in permutation(). It needs test = "permutation", otherwise an error of class nestimate_compare_actor_needs_permutation is raised. Several column names, outermost first (c("Group", "Student")), are nested levels: labels are shuffled at the level where they are assigned, within the units above it, and the ICC is that of the innermost level. Default NULL.

x

For the print() and plot() methods: a net_network_comparison object.

digits

For the print() and plot() methods: the decimals shown in printed values. Default 2.

type

For the plot() method: the view to draw, one per call. "networks" (default) draws each network once with cograph::splot(); "difference" draws the signed difference network of each pair; with test = "permutation" it is the graph of that pair's permutation() result (significant differences, starred); "edges" is a ranked dumbbell of the largest edge differences, and "nodes" the same for the centralities; "global" shows the 22 comparison metrics as points, plus the inference rows with their p-values (and bootstrap intervals) when test was run; "heatmap" the signed difference matrix; "scatter" the weights of one network against the other's; and "inference" a forest of the edge differences on the difference scale, with the credible intervals when the Bayesian test ran and the p-value printed per edge. "inference" needs test, otherwise an error of class nestimate_compare_no_test is raised.

pair

For the plot() method: the comparisons to draw. Default NULL, all of them. Give the pair names as printed ("A vs B"), the two network names in either order (c("A", "B")), one network name ("A", every pair it takes part in), or indices into the pair table (1, c(1, 3)). For type = "networks", it selects the networks taking part in the chosen pairs. A selection that matches no comparison raises an error of class nestimate_compare_unknown_pair.

combined

For the plot() method: whether a view of several pairs is one figure. With TRUE (default), the ggplot views facet by pair and the "networks" and "difference" views draw all panels on one base-graphics page. With FALSE, the ggplot views return a named list of single-pair plots, for iterating over or saving, and the base-graphics views draw one panel per page.

top_n

For the plot() method: the number of edges shown per pair in the "edges" and "inference" views, largest absolute difference first. Default 20.

measure

For the plot() method: the centrality measures shown in the "nodes" view. Default NULL, all measures of the comparison; a measure the object does not carry raises an error of class nestimate_compare_unknown_measure.

what

Deprecated alias for type, kept so existing calls keep working.

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:

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:

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 NULL, all of them. Give the pair names as printed ("A vs B"), the two network names in either order (c("A", "B")), one network name ("A", every pair it takes part in), or indices into the pair table (1, c(1, 3)). A selection that matches no comparison raises an error of class nestimate_compare_unknown_pair.

digits

The decimals kept in the numeric columns. Default 2. For the print() method: the decimals shown, by default those the table was made with.

...

Ignored. For [: the row and column indices.

x, object

A net_network_comparison object from compare_networks(). For the print() method and for subsetting with [ (as subset() does): a table returned by one of these verbs, whose rows and columns keep its digits.

measure

The centrality measures to keep in node_differences(). Default NULL, all measures of the comparison; a measure the object does not carry raises an error of class nestimate_compare_unknown_measure.

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:

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 mcml_pc fit with a score aggregation ("scaled", "composite", "mean", "median" or "loadings"). The descriptive aggregations ("average", "escoufier", "cancor") relate the clusters without ever forming a score and raise an error of class nestimate_no_composites.

...

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 NULL: every column except id_col and time. With neither action nor seq_cols, the frame must be one column or hold position columns named as a numbered run (T1, T2, ..., or 1, 2, ...), with nothing beside them but the id_col (and time) columns; anything else raises an error of class nestimate_bad_input, as does a column listed both here and in id_col or time.

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 id_col raises an error of class nestimate_bad_input (no column is taken by position). In a wide table, each row is one sequence and no id is inferred from the data: without id_col, a row-index column .rid is added. Default NULL.

action

The column holding each event's state; setting it declares an event log. Default NULL.

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

format

The output format: "frequency" (default), the count of each state per sequence; "onehot", whether each state occurs in the sequence (0/1); "edgelist", each pair of consecutive states (from, to); "follows", each event (act) paired with the event before it (follows).

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 data frame with a delimited column (field and sep);

  • a data frame in long (bipartite) form, one row per item in a transaction (field and by);

  • a 0/1 or TRUE/FALSE data frame or matrix, one row per transaction and one column per item, declared with format = "binary";

  • a wide sequence data frame or matrix with other values, whose rows are the transactions;

  • a plain list of character vectors, one per transaction.

A network object (netobject, netobject_group, cograph_network, tna) raises an error of class nestimate_bad_input; pass the data it was built from.

field

The column holding the items, which become the nodes. With sep, its values are split by sep; several column names pool the split values of each row. With by, it is the item column of a long table. Default NULL. Setting by or sep without field, or field without either, raises an error of class nestimate_bad_input, as does naming a column that data does not have, or setting any of the three for a list.

by

The column that defines the transactions of a long table: each of its values is one transaction, holding the distinct field values of its rows (for example "paper_id" or "session_id"). Default NULL, where items co-occur within the same row. It needs a single field column. Ignored, with a warning, when sep is set, since sep reads field as delimited.

sep

The separator that splits delimited field values, such as ";" or ",", matched literally; the split values are trimmed. Default NULL. See field for the combinations that raise an error.

similarity

How the co-occurrence count C_{ij} of items i and j, with item frequencies f_i and f_j, is turned into an edge weight. Default "none".

"none"

Raw co-occurrence counts.

"jaccard"

C_{ij} / (f_i + f_j - C_{ij}).

"cosine"

C_{ij} / \sqrt{f_i \cdot f_j} (Salton's cosine).

"inclusion"

C_{ij} / \min(f_i, f_j) (Simpson coefficient).

"association"

C_{ij} / (f_i \cdot f_j) (association strength, or probabilistic affinity index; van Eck & Waltman, 2009).

"dice"

2 C_{ij} / (f_i + f_j).

"equivalence"

C_{ij}^2 / (f_i \cdot f_j) (Salton's cosine squared).

"relative"

Each row divided by its sum (the diagonal included when diagonal = TRUE), so each row sums to 1: the weight from i to j is the share of i's co-occurrences that involve j. The matrix is no longer symmetric, so the network is directed and both directions of a pair are edges.

A zero denominator is replaced by 1, so an item without co-occurrences gets weight 0 rather than NaN.

threshold

The smallest weight kept: weights below it, on the scale of similarity, are set to zero. Default 0 (none).

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 1 (keep all).

diagonal

Whether the diagonal is kept. With TRUE (default) it holds each item's frequency (the number of transactions it appears in), transformed by similarity; with FALSE it is set to zero. Item frequencies for the similarity measures are the same either way.

top_n

How many of the strongest off-diagonal edges to keep: pairs in an undirected network, directed cells with similarity = "relative". Edges tied with the top_n-th weight are all kept, so a few more may remain, and the diagonal is not affected. Default NULL (all edges).

...

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 TRUE and FALSE) could be items or recoded positions, so with "auto" (default) they raise an error of class nestimate_bad_input. "binary" declares them items, one row per transaction, where a missing cell counts as no occurrence; it raises the same error on data with any other value.

Details

Six input forms are recognised from data and from which of field, by and sep are set:

  1. Delimited: field (one column) and sep. Each cell is split by sep, trimmed, and its distinct values form a transaction.

  2. Multi-column delimited: field (several columns) and sep. The split values of a row's columns are pooled into one transaction.

  3. Long bipartite: field and by. The distinct field values within each by group form a transaction.

  4. 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. Without format = "binary" such data is refused, since 0/1 columns could also be recoded positions.

  5. 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 class nestimate_bad_input, and a column called action and repeated column names are refused the same way.

  6. 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, discuss or review.

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 netobject built from sequences, a netobject_group, a net_clustering, a net_mmm or a tna model. A clustering, a mixture fit or a netobject_group gives one panel per cluster or group. A one-hot or association network, and a frame or matrix holding only 0 and 1 (unless cols declares a frame's columns as positions), raise an error of class nestimate_bad_input.

group

A vector of one group label per sequence (length nrow(x)), drawing one panel per group in the order of its factor levels (sorted for a character or numeric vector). NULL (default) uses the cluster assignments carried by a net_clustering, net_mmm or netobject_group; a group given overrides them. Panels are titled "Cluster <label>", whatever the grouping.

scale

What the y-axis shows: "proportion" (default) divides each time point by its total, so the bands fill 0 to 1; "count" keeps the counts, and the axis reaches the tallest stack.

geom

How the bands are drawn: "area" (default) as stacked polygons, "bar" as stacked bars.

na

Whether missing cells are drawn as an extra band coloured na_color. Default TRUE. With FALSE they are left out, and the proportions are shares of the observed states at each time point.

trim

Cuts the time axis (one number) or the time axis and the rows (two numbers); NA on either leaves that axis alone. Default NULL (no cut). The first number: a fraction in (0, 1) keeps the busiest time points that together hold that share of the observed states, wherever they sit, and the kept ones close up under their own labels (trim = 0.95); a value of 1 or more keeps the first that many time points (trim = 50). The second number ends each sequence earlier before the proportions are taken: a count keeps its first that many observed states, a fraction its first share of them (trim = c(0.9, 0.9)); no sequence is removed.

trim_clusterwise

For grouped plots with a fractional trim: FALSE (default) chooses one set of time points over all sequences, so every panel has the same time axis; TRUE chooses them within each group, so panels can differ in width.

state_colors

Colours for the state bands: an unnamed vector, one colour per state in sorted state order, or a named vector such as c(plan = "#0072B2"), where only the named states change and the rest keep the Okabe-Ito defaults. Names this plot does not draw are dropped with a message, so one palette can serve several figures. NULL (default) uses the palette stored on x with set_state_colors(), or the Okabe-Ito palette.

na_color

The colour of the missing-cell band. Default "grey90".

frame

Whether to draw a box around each panel, and axis lines. Default FALSE.

width, height

Size of a new graphics device, in inches, opened only in an interactive session (the other dimension defaults to 7). Default NULL (draw on the current device).

main

The plot title. With several panels on one figure it is drawn above them; with several panels and combined = FALSE it is not drawn. Default NULL.

show_n

Whether to add the number of sequences, "(n = N)", to the title of each panel. Default TRUE.

time_label

The x-axis label. Default "Time"; NULL or "" draws none.

xlab

Another name for time_label; when given, it wins.

y_label

The y-axis label. Default NULL: "Proportion" or "Count", following scale.

ylab

Another name for y_label; when given, it wins.

tick

Label every tick-th time point. Default NULL, which thins the labels to at most about 15.

ncol, nrow

The panel grid. Default NULL: with neither given, ncol = ceiling(sqrt(G)) and nrow = ceiling(G / ncol) for G panels; with one given, the other follows. With combined = FALSE the grid does not affect the layout, but ncol * nrow must still be at least the number of panels or an error is raised.

combined

Whether to draw all panels on one figure. TRUE (default) arranges them with graphics::layout(); FALSE draws each panel on its own page with its own legend, for knitr (fig.show = "asis") or for saving each panel to its own file. A single panel ignores it.

legend

Where the legend goes: "right" (default), "bottom" or "none".

legend_size

The legend text size. Default NULL, which scales it with the device width, between 0.65 and 1.2.

legend_title

A title for the legend. Default NULL (none).

legend_ncol

The number of legend columns. Default NULL: one column on the right, one row at the bottom.

legend_border

The colour of the swatch borders. Default NA (none).

legend_bty

The legend box: "n" (default) draws none, "o" draws one.

cols

For a wide data frame: the columns holding the time points. Needed when they are not a numbered run (T1, T2, ...), when one of them is called action, or when any other column sits beside them. Given for any other input, it raises an error of class nestimate_bad_input. Default NULL.

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 when na = TRUE.

palette

The fill colours, one per entry of levels.

groups

The panel labels ("all" when ungrouped), in the order of counts and proportions.

See Also

sequence_plot, build_clusters

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 outcome_model() result; anything else raises an error.

intercept

Whether to keep the intercept row. Default FALSE.

significant

Whether to keep only the terms whose corrected p-value (p_adj) is below alpha. Default FALSE.

alpha

The threshold for significant, between 0 and 1. Default 0.05.

digits

The decimal places of the numeric columns. Default 3; p_value and p_adj are never rounded.

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 netobject; a relative, frequency or co-occurrence netobject that carries its data, recounted with the network's own start and end states, concatenation, windows and one-hot units; a one-hot network built with build_network(), with its data, recounted the same way (a wtna() result is not read yet); an unscaled frequency, co-occurrence or reverse network without data, whose weights are the counts; a network without a declared method whose weights are non-negative whole numbers, read as counts; a tna model; a count matrix (non-negative whole numbers); or wide sequence data (a data frame or a character matrix) that holds a numbered run of positions (T1, T2, ...), from which a frequency network is built, other columns set aside with a message. For a frame without such a run, pass a network built with build_network(). When a network declares its method, counts are read from that method, never from the values: a scaled or relative network is recounted from its data. An association network, or any other network whose counts cannot be recovered, raises an error of class nestimate_bad_input; a matrix of probabilities raises an error, and so does a network of one state or with no observed transition (class nestimate_bad_input). A netobject_group, or a group_tna (read as the networks it converts to), gives one result per group. For the print() and plot() methods: an entropy_bayes() result; print() also takes a group result.

prior

The Dirichlet concentration added to every cell of the count matrix, a positive number. Default 0.5 (Jeffreys).

draws

The number of Monte Carlo posterior draws, at least 100. Default 4000.

ci

The mass of the credible intervals, between 0 and 1. Default 0.95.

min_share

The credibility threshold, a proportion in [0, 1): an edge is credible when the lower limit of the credible interval of its share of the entropy rate exceeds it. Default 0.01: the edge credibly accounts for at least 1% of the entropy rate.

base

The logarithm base, which sets the unit: 2 (default) for bits. Any finite number greater than 1; another value raises an error of class nestimate_bad_input.

seed

An integer that makes the draws reproducible. Default NULL. The session's own random stream is left as it was; a group uses the same seed for every group.

digits

For print() of a result: decimal places of the chain-level estimates. Default 3. A group result prints with three.

...

For the print(), summary() and plot() methods: not used.

object

For summary(): an entropy_bayes() result.

top

For plot(): the most edges to show, those with the largest posterior mean contribution. Default 25.

title

For plot(): the plot title. Default "Bayesian edge entropy contributions".

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 posterior mean, sd, ci_lower and ci_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 (in base units), the posterior mean and credible interval of its share of the entropy rate (a proportion), and the credible flag.

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 where credible and 0 elsewhere, 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 netobject or cograph_network with non-negative transition weights, a tna model, a numeric transition matrix, or wide sequence data (a data frame or a character matrix, one row per sequence) that holds a numbered run of positions (T1, T2, ...), from which a relative transition network is built; other columns are set aside with a message. For a frame without such a run, build the network with build_network() (⁠state_cols =⁠ or ⁠action =⁠) and pass that. An association network (cor, pcor, glasso, ising, mgm) or a matrix with negative entries raises an error of class nestimate_not_markov. A netobject_group is not accepted; pass one network at a time.

base

The logarithm base, which sets the unit: 2 (default) for bits, exp(1) for nats, 10 for hartleys. Any finite number greater than 1; another value raises an error of class nestimate_bad_input.

weight

What each edge's weight measures:

"contribution"

(default) \pi_i P_{ij} \log_b(1/P_{ij}), the edge's additive share of the entropy rate; all edge weights sum exactly to h(P). Heavy edges are transitions that are both frequent and unpredictable.

"surprisal"

\log_b(1/P_{ij}), the information content of observing the transition, ignoring how often it occurs. Heavy edges are rare, surprising transitions; a low surprisal marks an expected transition, which is the edge-level reading of predictability.

"production"

F_{ij} \log_b(F_{ij}/F_{ji}) with F_{ij} = \pi_i P_{ij}, the edge's contribution to the entropy production rate (irreversibility). It is positive on the dominant direction of a pair and negative on the reverse, and the two always sum to (F_{ij}-F_{ji}) \log_b(F_{ij}/F_{ji}) \ge 0. A pair with flow in one direction only has infinite production and is left out (weight 0); the number of such pairs is stored with the network's parameters. The total over the included pairs is the production rate. It is 0 for a reversible chain (detailed balance); when one-way pairs were left out, a total of 0 does not show reversibility, since such pairs mean the chain is not reversible.

scaling

How the weights are expressed. "none" (default) keeps them in base units. "share" (contribution only) gives each edge as a percentage of the entropy rate: the weights sum to 100, each one reads "this transition holds x% of the process's unpredictability", and they compare across networks whatever the number of states or the base. "chance" (surprisal only) divides by \log_b n, the surprisal of a transition when all n next states are equally likely: 1 is chance level, below 1 an expected transition, above 1 one rarer than chance. "share" with another weight, or "chance" with another weight, raises an error.

normalize

Whether rows that do not sum to 1 (a frequency network, a count matrix) are divided by their sums, with a warning. With FALSE, such rows raise an error. Default TRUE. A state with no outgoing transitions (a row summing to zero) is an error either way.

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), or sequences: a network built from sequences (a netobject, a grouped netobject_group, a tna model), prepared data, or a wide table or character matrix with one row per sequence and one column per position. Sequences are read in position order: each row is one actor, the position is the time, and the groups of a netobject_group become group. A network whose data are not sequences of states (an association or one-hot network) raises an error of class nestimate_bad_input.

action

The column of an event log holding each event's state. Default NULL, which reads data as sequences.

actor

The column identifying sequences: transitions are formed only between consecutive events of the same actor (within the same group). Default NULL, which reads the data as one sequence.

time

The timestamp column, which orders the events within each actor and places the windows on a time axis. Default NULL, which keeps the row order and uses the row number of the event that ends each transition as the axis. The column must be numeric, a Date or a POSIXct; a character timestamp fails, so parse it first.

group

A column splitting the data into parallel trajectories (for example a condition or an achievement level), each with its own windows. Default NULL (one trajectory, labelled "all"). A missing value in it raises an error of class nestimate_bad_input.

window

The number of transitions per window, at least 10. Default 500.

step

The number of transitions between the starts of consecutive windows. Default NULL, which uses window %/% 5 (at least 1).

base

The logarithm base, which sets the unit: 2 (default) for bits. Any finite number greater than 1; another value raises an error of class nestimate_bad_input.

x

For the print() and plot() methods: an entropy_trajectory() result.

digits

For print(): decimal places of the entropies. Default 3.

...

For the print(), summary() and plot() methods: not used.

object

For summary(): an entropy_trajectory() result.

normalized

For plot(): whether to draw entropy_norm instead of the raw entropy. Default FALSE.

span

For plot(): the loess span of the trend line. Default 0.4. A group gets a trend line when span times its number of windows is at least 4 (10 windows at the default); a group with fewer windows is drawn as its windows joined by a line, with a nestimate_sparse_trajectory warning naming it. A group with enough windows whose loess fit still warns is drawn the same way, with a nestimate_trend_not_fitted warning giving loess's message.

title

For plot(): the plot title. Default "Transition entropy over time".

iter

For plot(): the number of bootstrap resamples behind the confidence band of each trend. Default 200; 0 draws the trends without a band.

ci_level

For plot(): the coverage of the band. Default 0.95.

seed

For plot(): a seed for the resampling. It applies to this call only: the session's random state is restored afterwards. Default NULL.

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 no time column), time_start and time_end (the time, or row number, of the window's first and last transition), n_transitions, n_states (distinct states in the window), entropy (in base units per transition) and entropy_norm (divided by \log_b of 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 build_network().

method

The estimator, as in build_network(). Default "relative", kept for backward compatibility; build_network() has no default.

params

Settings for the estimator, as a named list, as on the method's page (for example build_glasso()). Default list().

scaling, threshold

As in build_network().

level

Multilevel decomposition for the association methods, as in build_cor(). Default NULL.

...

Further arguments for build_network(), such as actor, action, time or group.

Value

A netobject, exactly as build_network() returns it (a netobject_group or netobject_ml when ... or level asks for one).

See Also

build_network

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 simplicial_complex from build_simplicial().

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)


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 predict_links() result.

true_edges

The known edges: a data frame with columns from and to (every row is an edge, whatever its other columns, such as a weight, hold), or a matrix whose non-zero cells are edges. Its row names name both its rows and its columns (column names are not read), so its columns must be in the same order as its rows (column names that differ from the row names raise a warning of class nestimate_ignored_argument); without row names, the nodes of pred are used. For a directed prediction, pairs are matched by from and to, direction included; for an undirected one, in either order, so ⁠(C, A)⁠ matches the listed pair ⁠(A, C)⁠.

k

The cut-offs for precision@k. Default c(5, 10, 20). A k larger than an index's number of predictions gives NA.

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 netobject, a group of networks (netobject_group), a tna-family model, an mcml or a weight matrix, as for extract_transition_matrix().

threshold

Cells whose absolute weight is at most threshold are dropped. A single finite number of at least 0, otherwise an error is raised (class nestimate_bad_input for a negative value); default 0.

include_self

Whether to keep self-loops (a state followed by itself), TRUE or FALSE. Default FALSE.

sort_by

The row order: "weight" (default) by decreasing weight, "from" by source then target state, "to" by target then source state, or NULL for the order of the weight matrix (column by column). Any other value raises an error.

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 netobject, a group of networks (netobject_group), a tna-family model, an mcml, or a list holding an initial element. Input from which neither initial probabilities nor a weight matrix can be read raises an error.

x

For the print() method: a nest_initial_probs.

...

For the summary() method: ignored. For the print() method: passed on to the vector print.

object

For the summary() method: a nest_initial_probs.

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 order is given. A unit's rows need not be contiguous: rows of other units in between are not part of its pathways.

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 group and then by it. Default NULL, which keeps the row order.

type

The cut to make:

"unit"

(default) one pathway per unit. With terminal, each unit is cut after its last terminal state, so the pathway ends on an outcome rather than on whatever followed; units without a terminal state are left out.

"segments"

consecutive, non-overlapping pathways: each unit is cut after every terminal state, so each pathway ends on one. Events after a unit's last terminal state belong to no pathway.

"anchored"

one pathway per occurrence of anchor, closing at the first terminal state after it. Pathways may overlap, and events between a terminal state and the next anchor belong to none.

anchor

The single state that opens a pathway when type = "anchored", where it is required; the other cuts ignore it. It may also be one of the terminal states: a pathway then closes at the next terminal state after the anchor, not at the anchor itself. Default NULL.

terminal

The states that close a pathway, the closing state included. Required for "segments" and "anchored"; optional for "unit", where it cuts each unit after its last terminal state. Default NULL.

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 "Unresolved". The label becomes the last state of path, counts in length, and is the value of closes; the observed last state is kept in ends. Default NULL (no label).

sep

The separator placed between states in path. Default " -> ".

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 nestimate_data object from prepare(); a long event log (set action); a wide data frame or character matrix; or a netobject, netobject_group, cograph_network or tna model built from sequence data. A group_tna (package tna) is read as the group of networks it converts to (see as_netobject()). A network estimated with an association method (cor, pcor, glasso, ising, mgm) or from one-hot codes, a network built from a matrix (it holds no sequences), and any other input raise an error of class nestimate_bad_input.

cols

The state columns of a wide data frame; the other columns are the sequences' covariates. Default NULL: the frame must be a single column or hold its positions as a numbered run of names (a shared prefix and a number, T1, T2, ..., or 1, 2, ...), and the columns outside the run, and numeric columns beside it, are covariates. Any other frame, or columns holding only 0 and 1 (which could be one-hot codes), then raise an error of class nestimate_bad_input; listing them in cols reads them as positions. A name in cols that is not in the frame raises the same class. Ignored for prepared data, event logs (where a listed name must still exist) and model objects.

actor, action, time

The actor, action and timestamp columns of a long event log. Setting action declares x an event log and passes actor and time to prepare(). On a wide table without action, the columns they name must exist, or an error of class nestimate_bad_input is raised. The columns they name are covariates, never positions: they are left out of the states (also from a numbered run) and kept with the covariates, and naming one of them in cols too raises an error of class nestimate_bad_input. Default NULL.

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

...

Further arguments passed to prepare() for a long event log, such as time_threshold or order; ignored otherwise.

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

prepare, sequence_patterns

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 netobject, a group of networks (netobject_group), a tna-family model, an mcml, a list holding the matrix as weights (or, failing that, transition_matrix or transition), or a weight matrix. Anything else raises an error.

type

Which matrix to return. "raw" (default) returns the weights as stored. "scaled" divides each row by its sum, so the rows of a count matrix become transition probabilities; a row that sums to zero is left as it is.

x

For the print() method: a nest_transition_matrix.

...

For the summary() method: ignored. For the print() method: passed on to the matrix print.

object

For the summary() method: a nest_transition_matrix.

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 NULL. Column names give no role: a column called Action with nothing declared raises an error of class nestimate_bad_input, and so does an action not in data.

id

The column(s) identifying sequences. Default NULL. In an event log, each unique combination of their values is one sequence, and without id all rows form a single sequence. In a wide table, they are left out of the state columns. A column not in data raises an error of class nestimate_bad_input.

time

The column that orders the events of each sequence in an event log. Default NULL: events keep their row order. A wide table does not use it and leaves it out of the positions. A column not in data, or one also listed in cols, raises an error of class nestimate_bad_input.

cols

The state columns of a wide table; setting them declares a wide table. Default NULL. With neither action nor cols, the frame must be one column or hold position columns named as a numbered run (T1, T2, ..., or 1, 2, ...), with nothing beside them but the id (and time) columns; anything else raises an error of class nestimate_bad_input, as does a listed column not in data. A single column is read as one position per row, so it counts no transitions; declare an event log with action.

format

How to read data. "auto" (default) reads an event log when action is set and a wide table otherwise. "long" forces an event log and needs action. "wide" forces a wide table and reads every column outside id and time (or the columns in cols) as a position, without the check on undeclared columns; it ignores action, so that column is counted as a position unless cols leaves it out. "long" ignores cols.

object

For the summary() method: a nest_transition_counts matrix from frequencies().

...

For the summary() method: ignored.

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 build_hypergraph() or bipartite_groups().

type

The centralities to compute, any of "clique", "Z" and "H", returned in the order given. Default "clique". "Z" and "H" need a uniform hypergraph (every hyperedge with two or more members has the same size); on any other they raise an error of class nestimate_nonuniform_hypergraph.

max_iter

The largest number of power-iteration steps for "Z" and "H". Default 1000. "clique" is solved directly and ignores it.

tol

The convergence tolerance for "Z" and "H": the iteration stops once the L1 change between successive iterates is below it. Default 1e-8. An iteration that does not get there within max_iter steps, or that stops without solving the eigen-equation, warns with class nestimate_no_converge.

normalize

How each vector is scaled. TRUE (default) gives it unit Euclidean (L2) norm; FALSE divides it by its largest absolute entry, so the top node scores 1, the scale of igraph::eigen_centrality().

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 net_hypergraph, as for hypergraph_laplacian().

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 hypergraph_laplacian(). Defaults "zhou" and NULL.

nstart

The number of random starts k-means tries, keeping the best. Default 25.

seed

A whole number that makes the k-means starts reproducible. The session's own random stream is left as it was. Default NULL.

x

For print(), plot() and node_clusters(): a result of hypergraph_cluster().

...

For the methods: ignored.

object

For the summary() method: a net_hypergraph_cluster object.

what

For the plot() method: the panel to draw. "spectrum" is a scree plot of the smallest eigenvalues with the k used marked, so the eigengap after k can be read; "embedding" places the nodes on the first two embedding dimensions, labelled, coloured and shaped by cluster and sized by stationary probability, which is the geometry k-means clustered (beyond nine clusters the colours repeat and the shape tells the clusters of one colour apart); "both" (default) draws the two side by side.

n_values

For the plot() method: how many of the smallest eigenvalues the spectrum panel shows. Default NULL, which shows min(3 * k, n_nodes).

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: node and cluster. Clusters are labelled "Cluster 1", "Cluster 2", ... in the order they first appear among the nodes.

embedding

The node-by-k spectral embedding k-means clustered, each row of unit length, with columns dim1 to dimk.

k, type

The number of clusters and the Laplacian type.

eigenvalues

The full spectrum of the Laplacian, increasing.

eigengap

The (k + 1)-th minus the k-th eigenvalue.

sizes

A data frame of cluster and size.

pi

The stationary distribution of the walk, named by node.

n_nodes, n_hyperedges

The size of the hypergraph.

params

The edge_weights used, nstart, seed and 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 build_hypergraph() or bipartite_groups(), with at least two nodes and one hyperedge. Raises nestimate_hypergraph_disconnected when the hypergraph is not connected, since it then has no unique stationary distribution; analyse its components separately.

type

The Laplacian. "zhou" (default) is the Zhou et al. (2006) Laplacian on the binary incidence pattern; "random_walk" is the Hayashi et al. (2020) random-walk Laplacian on the weighted incidence.

edge_weights

Positive hyperedge weights, one per hyperedge in the order of the incidence columns. Default NULL, which gives unit weights for "zhou" and, for "random_walk", the heuristic of Hayashi et al.: the population standard deviation of each hyperedge's positive incidence cells plus one, which is 1 on a binary incidence. A vector of the wrong length, or with a value that is not finite and positive, raises an error.

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 net_hypergraph, from build_hypergraph() or bipartite_groups(). Any other object raises an error.

x

For the print() method: a hypergraph_measures object.

...

For the print() method: not used.

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:

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)
hyperdegree

The number of hyperedges containing each node.

node_strength

Total participation: for node i, \sum_{e \ni i} |e|. A node in many large hyperedges has high strength.

max_edge_size

The size of the largest hyperedge containing each node (0 for a node in none).

co_degree

An n_nodes x n_nodes matrix: ⁠co_degree[i, j] = |{e : i, j in e}|⁠, the number of hyperedges containing both nodes i and j. The diagonal is zero.

Hyperedge-level (one value per hyperedge, or m x m)
edge_sizes

The hyperedge sizes |e|.

edge_pairwise_overlap

An m x m matrix of ⁠|e_i intersect e_j|⁠. The diagonal is zero.

overlap_coefficient

An m x m matrix 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.

jaccard

An m x m matrix of the symmetric overlap index ⁠|e_i intersect e_j| / |e_i union e_j|⁠. The diagonal is zero.

Global (scalars)
density

For 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_size

The mean of edge_sizes.

size_distribution

The count of hyperedges of each size, passed through from hg.

intersection_profile

The 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_participation

The fraction of node pairs that appear together in at least one hyperedge (0 with fewer than two nodes).

n_nodes, n_hyperedges

The 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 net_hypergraph, as for hypergraph_laplacian().

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 NA for the unlabelled ones. Required. It must hold at least two distinct classes; a name that is not a node, or an unnamed vector of the wrong length, raises an error.

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

type, edge_weights

The Laplacian and its hyperedge weights, passed to hypergraph_laplacian(). Defaults "zhou" and NULL.

x

For print(), plot(), label_predictions() and label_scores(): a result of hypergraph_transduction().

...

For the methods: ignored.

object

For the summary() method: a net_hypergraph_transduction object.

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, NA for an unlabelled node), predicted, score (the winning class's score) and margin (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_weights used.

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 mcml_pc object from build_mcml_pc(). A fit that carries no item table raises an error of class nestimate_no_loadings.

...

Ignored.

misfit

Which items to return: NULL (default) returns every item, TRUE only those whose strongest cross-cluster connection exceeds their own-cluster loading, and FALSE only those that fit where they were assigned.

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 build_network() with method "relative" or "frequency" (or a bare cograph_network of one), a grouped one (netobject_group), a tna model or a group_tna (one landscape per group), or a wide sequence data frame or matrix. A network must count one-step transitions (a window wider than one position raises an error) and carry its sequences; a network of another method (for example "glasso") raises an error of class nestimate_not_markov. For the print() and plot() methods: a net_landscape_surface object.

measure

The per-sequence measures to trace, one surface each: one or more numeric columns of sequence_metrics(). Default "longitudinal_entropy". A name that is not a numeric column, or a measure that is the same for every sequence, raises an error of class nestimate_bad_input.

states

Every state, each named once, in drawing order. Default NULL, the alphabetical order. A vector that leaves out, adds or repeats a state raises an error of class nestimate_bad_input.

k

The number of nearest sequences each slice is weighted over, at least 5. Default 30, capped at the number of usable sequences.

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

cols

For a wide data frame: the columns holding the positions. Needed when they are not a numbered run (T1, T2, ...) or one of them is called action; such a frame without cols raises an error of class nestimate_bad_input. Default NULL.

object

For the summary() method: a net_landscape_surface object.

ends

For the summary() method: TRUE (default) compares the low and the high end of each measure; FALSE returns every slice.

...

Ignored.

digits

For the print() method: decimal places. Default 2.

max_stay

For the plot() method: the longest expected stay drawn, in steps, a number above 1. Cups of states whose expected stay is longer (including states never left in a slice) are drawn at the depth log(max_stay), a display floor only. Default 50.

theta, phi

For the plot() method: the viewing angles passed to graphics::persp(). Defaults 10 and 30.

ncol

For the plot() method: panels per row. Default NULL, one column per measure and one row per network.

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 build_network() with method "relative" or "frequency" (or a bare cograph_network of one), a grouped one (netobject_group), a tna model or a group_tna (one landscape per group), or a wide sequence data frame. A covariate is read from the network's metadata, which build_network() fills with the numeric columns of a wide data frame, or from a data frame's columns beside the positions. A network must count one-step transitions (a window wider than one position raises an error) and carry its sequences; a network of another method (for example "glasso") raises an error of class nestimate_not_markov. For the print() and plot() methods: a net_landscape_trend object.

along

The axis: "phase" (default), or the name of a numeric per-sequence covariate. A name that is not a numeric covariate of the sequences, a covariate that is the same for every sequence, or one that varies within a concatenated sequence raises an error of class nestimate_bad_input.

depth

The height: "stay" (default) or "occupancy", as described above.

states

Every state, each named once, in drawing order; with depth = "occupancy" it also sets which states share a ridge. Default NULL, the alphabetical order. A vector that leaves out, adds or repeats a state raises an error of class nestimate_bad_input.

window

With along = "phase": the time steps per window, at least 2. Default 5. A window longer than the sequences raises an error of class nestimate_bad_input. Not used with a covariate, but still checked.

k

With a covariate: the number of nearest sequences each slice is weighted over, at least 5. Default 30, capped at the number of usable sequences. Not used with along = "phase", but still checked.

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 20. Not used with along = "phase", but still checked.

iter

The number of bootstrap resamples of sequences, a non-negative whole number. Default 500; 0 leaves the intervals NA.

ci_level

The interval level, a number between 0 and 1. Default 0.95.

seed

A seed for the resampling. It applies to this call only: the session's random state is restored afterwards. Default NULL.

cols

For a wide data frame: the columns holding the positions. Needed when they are not a numbered run (T1, T2, ...) or one of them is called action; such a frame without cols raises an error of class nestimate_bad_input. Default NULL.

object

For the summary() method: a net_landscape_trend object.

...

Ignored.

digits

For the print() method: decimal places. Default 2.

type

For the plot() method: "lines" (default) draws one line per state with its interval band, the states told apart by colour, point shape, line type and a label at the end of each line; "surface" draws a 3D graphics::persp() landscape with the states across and the second axis in depth, one panel per network on a shared height scale, ridges included with depth = "occupancy".

theta, phi

For plot(type = "surface"): the viewing angles. Defaults 10 and 30.

state_colors

For the plot() method: colours for the states, for this figure only. Named, c(state = "#0072B2"), it overrides the states it names; unnamed, it gives one colour per state in states order. Default NULL: the colours of the network the result came from (set with set_state_colors()), Okabe-Ito for the rest, as every figure of that network draws them.

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 mcml_pc object that carries its raw data; one built from a network without data raises an error, and so does an older saved fit with custom weights, which must be rebuilt with build_mcml_pc() to keep its weighting. For the print() and plot() methods: a pc_loading_stability object.

iter

The number of bootstrap replicates, at least 2. Default 200; each replicate re-estimates the node-level network, so this is slower than a plain bootstrap.

ci_level

The tail level of the percentile intervals: 0.05 (default) gives 95% intervals.

seed

An integer that makes the resampling reproducible. Default NULL. The session's own random stream is left as it was.

digits

For the print() method: the decimal places of the numeric columns. Default 3.

...

For the print(), summary() and plot() methods: ignored.

object

For the summary() method: a pc_loading_stability object.

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_upper and sign_flips (the share of replicates in which the item's sign differed from the observed one).

boot_weights

The iter x 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

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_1 to Project_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 follows order_in_session. With the default time_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, use time = "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 in ai_long (Ask, Delegate, Execute, Explain, Investigate, Plan, Repair, Report), 17 in total.

cluster

Character high-level cluster of the code. human_long uses Directive, Evaluative and Metacognitive; ai_long uses 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 "Actor"; a missing column raises an error.

time_col

The column that orders the actions within a sequence. Default "Time". Its values only order the actions; they do not set the column numbers, so gaps between time points are not kept. Actions with the same time keep their row order. When the column is absent, the row order is used.

action_col

The column holding the actions (states). Default "Action"; a missing column raises an error.

time_prefix

The prefix of the position columns in the output. Default "V".

fill_na

How to handle sequences of different lengths. With TRUE (default), shorter sequences are padded with NA, so every row has the columns of the longest sequence. With FALSE, only the positions present in every sequence are kept, so longer sequences are cut to the length of the shortest.

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 mcml built from sequence data, or an mcml_pc from build_mcml_pc(). An mcml built from a matrix or an edge list holds no sequences to count, so it raises an error of class nestimate_no_expand_source, even with expand = NULL; a name in expand that is not a cluster is reported first.

expand

The clusters to expand into their member states. NULL (default) collapses every cluster, which reproduces the macro layer; "all" or TRUE expands every cluster, so each state is its own node. A name that is not a cluster raises an error. For an mcml_pc, any value other than NULL raises an error of class nestimate_no_expand: there are no sequences to count again.

method

The estimator passed to build_network(). Default "relative" (row-normalised transitions). For an mcml_pc, giving it raises an error: the estimator was set by build_mcml_pc().

scaling, threshold, params

Passed to build_network() for the re-counted network: scaling (default NULL, none), threshold (default 0) and params (default list()), as there. For an mcml_pc, giving any raises an error, as for method.

...

Further arguments for build_network(), such as start or end. For an mcml_pc, giving any raises an error, as for method.

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

build_mcml, as_tna

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 action set) or wide sequences, as a data frame.

actor, action, time

The columns of a long event log, as in build_network(). Column names are not read: without action the data is read as wide sequences, and a frame whose roles cannot be told raises an error of class nestimate_bad_input, as does a name that is not a column of data. Default NULL.

metric

The discrepancy metric, computed on the two scaled weight vectors. "abs_diff" (default) is the absolute difference; "chord_dist" the absolute difference after each vector is scaled to unit length (chord distance on the unit sphere); "atanh_diff" the absolute difference of the Fisher z (atanh()) transforms, with values capped at 1 - 1e-6, so it needs weights in [0, 1) and is not meaningful with scale = "none"; "geom_norm_diff" the absolute difference after each vector is divided by its geometric mean (of the weights plus 0.001, so zeros are allowed), which enlarges small edges; and "cv_inflation" the absolute difference after each vector is divided by its standard deviation (at least 0.001).

scale

How the two weight matrices are put on a common scale before differencing. "tna_range" (default) rescales the counts linearly into the ⁠[min, max]⁠ range of the probabilities and leaves the probabilities as they are, so the difference is in probability units. "rank_minmax" replaces each matrix's values by their ranks scaled to [0, 1] (ordinal). "minmax" scales each matrix to [0, 1] separately, so the two maxima map to the same value although their native ranges differ. "none" uses the raw weights. A matrix whose weights are all equal has no range to rescale and maps to the middle of the target range (0.5, or for "tna_range" the middle of the probability range).

format

The input format passed to build_network(). "auto" (default) reads wide sequences when action is NULL and an event log otherwise; "long" and "wide" force a reading. "long" needs action; without it, an error of class nestimate_bad_input is raised.

x

For the print() and plot() methods: a magnitude_difference object.

...

For the plot() method: further settings of the drawing.

  • "stacked": threshold (the magnitude marked "small" in the colour key, default 10% of the largest), the radii r_inner, r_outer and gap_rad, and the labels label_offset, label_size and src_label_size;

  • "circular": self_loops (default TRUE), label_offset and edge_curve.

The print() and summary() methods ignore it.

object

For the summary() method: a magnitude_difference object.

n

For the summary() method: the number of edges to return, the largest differences first. Default NULL returns every edge.

type

For the plot() method: the kind of plot. "stacked" (default) is a polar portrait with one sector per source state and one wedge per edge, grey up to the smaller of the two scaled weights and coloured by the magnitude difference from there to the larger; edges absent from both views are left out. "circular" is a chord-style diagram of the signed difference (tna - ftna), its colour giving the sign and its width and opacity the magnitude.

min_show

For type = "circular": edges whose magnitude difference is below this fraction of the largest are left out. Default 0.01.

title

For the plot() method: the plot title. Default NULL, which names the metric and the scale.

state_colors

For the plot() method with type = "stacked": colours for the source states, for this figure only, named (c(state = "#0072B2")) or one per state in states order. Default NULL: Okabe-Ito dealt in alphabetical order, as every figure deals them.

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, ftna and tna (the scaled weights), signed (tna - ftna) and value (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 NA for a missing observation. Without cols, the frame must be one column or a numbered run of positions (T1, T2, ...); other columns beside them raise an error of class nestimate_bad_input.

state

The label written into the leading missing cells, a single non-empty string. Default "Start". A label that already occurs in data is made unique with a suffix (⁠_1⁠, ⁠_2⁠, ...) and raises the warning nestimate_state_collision, so the marker is never confused with an observed state.

cols

The columns holding the positions, in order; only they are returned. A name not in data raises an error of class nestimate_bad_input. Default NULL (every column).

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 NULL, which treats the whole log as one sequence.

time

The column ordering the events within each actor: numeric, a Date or a POSIXct. Default NULL, which keeps the row order.

n

The number of phases, a whole number of at least 2. Default 2.

labels

The labels of the phases, in order, n distinct non-empty strings. Default NULL, which uses "1", "2", ..., "n".

name

The name of the new column. Default "phase". A column of that name already in data raises an error of class nestimate_bad_input.

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 NA for a missing observation. Without cols, the frame must be one column or a numbered run of positions (T1, T2, ...); other columns beside them raise an error of class nestimate_bad_input.

state

The label written into the trailing missing cells, a single non-empty string. Default "End". A label that already occurs in data is made unique with a suffix (⁠_1⁠, ⁠_2⁠, ...) and raises the warning nestimate_state_collision, so the absorbing marker is never confused with an observed state.

cols

The columns holding the positions, in order; only they are returned. A name not in data raises an error of class nestimate_bad_input. Default NULL (every column).

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 netobject or netobject_group built with its data, or a prepare() result (its sequence data is used). A data frame is read whole, so it must hold only positions: one column, or columns named as a numbered run (T1, T2, ...); anything else, such as an id column beside the positions, a column named action, or columns holding only 0 and 1, raises an error of class nestimate_bad_input, and the positions are then declared with build_network() (state_cols, or action for an event log) and the network passed instead. A one-hot or association network, a network built from an edge list (such as a layer of an edge-list build_mcml()), an mcml object, and any list other than a plain list of state vectors raise the same error. Sequences are split at missing values: no window spans an NA, and pieces with fewer than two states are dropped. A tna model (package tna) or a bare cograph_network gives the sequences it carries, and a group_tna one result per group.

max_order

The highest order to test, at least 1. Default 3. It is lowered, with a message, to one less than the length of the longest sequence.

n_perm

The number of within-context permutations per order, at least 1. Default 500. The smallest attainable p-value is 1 / (n_perm + 1), and a test rejects only when its p-value is below alpha, so with 1 / alpha - 1 permutations or fewer (19 for the default alpha) no order above 0 can be selected.

alpha

The significance level for the sequential selection, strictly between 0 and 1. Default 0.05.

parallel

Whether to run the permutations with parallel::mclapply(). Default FALSE. Ignored on Windows, where they run serially. With TRUE the permutations are reproducible from seed only under RNGkind("L'Ecuyer-CMRG"); under the default generator they differ from run to run.

n_cores

The number of cores for parallel = TRUE, a single number of at least 1. Default 2.

seed

An integer that makes the permutations reproducible (with parallel = TRUE, only under the L'Ecuyer-CMRG generator). Default NULL. The session's own random stream is left as it was; a group's networks are each started from the same seed.

dof

How the AIC and BIC columns count each layer's parameters: "paths" (default) counts every transition the observed first-order topology allows, as in Scholtes (2017) and pathpy; "observed" counts the transitions seen in the data, the rule before Nestimate 0.9.28. The permutation test does not use it.

x

For the print() methods: a net_markov_order or net_markov_order_group; for the plot() method: a net_markov_order.

...

For the print() method of a net_markov_order_group: passed on to the print() of each group. For the other methods: not used.

object

For the summary() method: a net_markov_order.

panel

For the plot() method: which panels to draw. "both" (default), "ic" (the fit across orders) or "permutation" (the permutation nulls); a single panel is returned as a ggplot. When no tested order has a permutation null (every test has 0 degrees of freedom, as for constant sequences), only "ic" can be drawn and the other two raise an error of class nestimate_bad_input.

combined

For the plot() method with panel = "both": TRUE (default) draws the two panels side by side and returns them as one gtable when gridExtra is installed, or, without it, draws them with grid viewports and returns the two ggplots (ic, permutation) invisibly as a named list. FALSE returns that list invisibly without drawing. Ignored for a single panel.

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() and plot() and not used in the selection.

test_table

The test table, one row per order from 0 to max_order, with columns order, loglik, AIC, BIC, df, g2, p_permutation, p_asymptotic and significant. The order-0 row has NA in the test columns (df to significant).

permutation_null

The permutation null of G^2 at each order, a list of numeric vectors named order_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_order is 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^2 for each order, one facet each, with the observed G^2 as a vertical line labelled with its p-value and coloured by whether the test rejects at alpha.

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 passage_time(): a netobject, bare cograph_network or tna model with non-negative transition weights, a non-negative numeric transition matrix, or a wide sequence data frame or character matrix (a "relative" network is estimated from it). A netobject_group gives one result per group. An association network or negative weights raise nestimate_not_markov. For print() and plot(): a markov_stability() result.

normalize

Whether to rescale rows that do not sum to 1 so that they do, with a warning, as for a "frequency" network. With FALSE, such rows raise an error. A state with no outgoing transitions (a zero row) raises an error either way. Default TRUE.

...

Not used (print() of a group passes it on to each group's print(), which ignores it).

object

For the summary() method: a net_markov_stability.

metrics

For the plot() methods: the metrics to draw, one panel each, any of "persistence", "stationary_prob", "return_time", "sojourn_time", "avg_time_to_others" and "avg_time_from_others". Default all six.

combined

For plot() of a single network: TRUE (default) draws the metrics as panels of one plot; FALSE returns a named list of one-panel plots, one per metric, to print or save separately. Ignored for a group, whose plot() always draws one plot, with a warning of class nestimate_ignored_argument.

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) and avg_time_from_others (the mean first passage time from the others to the state). persistence and stationary_prob are rounded to 4 decimals, the times to 2.

mpt

The net_mpt from passage_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

passage_time

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 net_mogen object from build_mogen().

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 NULL, the order the model selected. Order 0 has no transitions, so when the model selected order 0, give order explicitly; otherwise mogen_transitions() stops.

min_count

The smallest observed count a transition needs to be listed. Default 1, every observed transition. A value below 1 also lists the transitions that never occurred, with count and probability 0: every pair of observed contexts where the second continues the first (at order 1, every pair of states).

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 actor column) are left out; a var1 or var2 that is not a column of data, or no complete rows, raises an error.

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 10. If fewer than two categories of either variable remain, an error is raised.

test

The test reported: "chisq" (default) for Pearson's chi-square test, or "fisher" for Fisher's exact test: exact for a 2 x 2 table, and otherwise with a p-value simulated from 10,000 tables (so it changes with the random seed and cannot fall below 1/10,001). Cramer's V and the residuals come from Pearson's chi-square (V from the statistic without Yates' correction). Used when nested = FALSE; given with nested = TRUE it is ignored with a warning of class nestimate_ignored_argument.

percentage_base

What the pct column and the "percent" tile label are a percentage of: "total" (default) the whole table, "row" each level of var1, "column" each level of var2.

tile_label

What to print inside each tile: "count" (default), "percent", "residual", "category" (the var2 level) or "none".

title

The plot title. Default "" (none).

...

Further styling for the flat mosaic:

  • labels: col_label_side, row_label_side, col_label_angle, row_label_angle, label_size, min_label_h and min_label_w;

  • legend: show_legend, legend_position, legend_size and legend_title;

  • fill: range and palette (default the ColorBrewer RdBu ramp);

  • pct_base, which overrides percentage_base in the plot only.

Column labels turn vertical when there are more than 6 columns; col_label_angle sets an angle. Any other name raises an error. For the plot() method: the same styling and title, overriding what the fit stored; for the print() and summary() methods: ignored.

nested

Whether the rows are nested in actors and the test should allow for it. Default FALSE: every row is independent, as before. TRUE reports nested_method and needs actor; see Nested data.

nested_method

With nested = TRUE, the test: "rao_scott" (default), "donner_klar", "cmh", "gee" or "glmm". A test that cannot run on the design raises nestimate_bad_input; "glmm" needs the lme4 package.

actor

With nested = TRUE (required then): the name of the column whose values identify the actors, or several names for nested levels, outermost first (e.g. c("Group", "Actor")). nested_method and actor given with nested = FALSE are ignored with a warning of class nestimate_ignored_argument.

report

Whether to report the test: TRUE draws it as the plot subtitle and prints it as a one-row data frame with the columns of mosaic_test() but note. Default FALSE. The test is always in the stats table and in print().

x

For the plot() and print() methods: a mosaic_analysis.

object

For the summary() method: a mosaic_analysis.

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, NA where it is undefined and drawn at 0) and pct (on percentage_base); expected and residual are rounded to 3 decimals, pct to 2.

stats

A one-row data frame: test, statistic, df, df2, p_value, cramers_v, effect_size, n, clusters, design_effect and icc, rounded (statistic and cramers_v to 3 decimals, p_value to 4 significant digits). statistic and df are NA for Fisher's test. df2 (the denominator degrees of freedom of the Rao-Scott F), clusters, design_effect and icc are NA where the test has none.

test

The htest object of the test reported; NULL for a nested test.

actor

The actor column names, or NULL.

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 var1 and var2.

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 so plot() 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_effect is 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 of ⁠p_ij - p_i. p_.j⁠); with one row per cluster it is chisq.test()'s, and it is NA where 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), where rho is the ANOVA intracluster correlation of var2, 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. icc is rho; 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 (clusters counts 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 var2 given var1 with an identity link and independence working correlation; Wald chi-square with the cluster-robust (sandwich) covariance for equal distributions of var2 across var1, 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 class nestimate_bad_input is 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 of var2 within the level of var1 minus 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-var1 and cluster-by-var2 at every level of actor, so several columns give nested random effects (outermost first); Wald chi-square on the interaction. Fitted by lme4::glmer(nAGQ = 0), a faster, less exact approximation than the default Laplace fit; needs lme4, and a failed fit raises an error of class nestimate_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

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 netobject, netobject_group, mcml or htna network, a contingency table (two-way, or three-way with the clusters as the third dimension), a numeric count matrix, or a data frame in long form (see x_var, y_var and weight). A tna model or a group_tna (package tna) is first rebuilt as a network from its own sequences (see as_netobject()).

...

With style = "flat": styling arguments for the flat mosaic of a network, table or matrix; an unknown name raises an error that lists the valid ones. Raises nestimate_bad_input when the data-frame method, or the mcml method with style = "classic", gets an argument it does not take; the other methods ignore such an argument with a warning.

xlab, ylab

Axis titles. The network and mcml methods draw none by default (NULL); the table and matrix methods default to "Row" and "Column"; a data frame defaults to the x_var name and "Proportion". Not drawn with style = "flat".

range

The lower and upper limits of the residual colour scale, two increasing numbers; residuals beyond them take the end colours. Default NULL, which fits the symmetric range c(-M, M), with M the largest absolute residual (at least 1), so no tile is clipped. c(-4, 4) matches tna's display.

top_angle, left_angle

Rotation, in degrees, of the column labels on top and the segment labels on the left. Default NULL: 90 when an axis has more than three levels, 0 otherwise. Not used with style = "flat" or for the per-cluster mcml panels.

residuals

How the standardised residuals are computed. "permutation" (default) shuffles one variable's labels against the other n_perm times, which keeps both margins, and gives each cell (observed - mean) / sd over the shuffles; a cell that never varies gets 0. It does not rely on large expected counts, so it suits sparse tables. "asymptotic" gives the adjusted residuals of stats::chisq.test(), (O - E) / sqrt(E (1 - p_row) (1 - p_col)), as vcd and tna do. Used when nested = FALSE; given with nested = TRUE it is ignored with a warning of class nestimate_ignored_argument.

n_perm

The number of shuffles for residuals = "permutation", at least 2. Default 500; use 1000 or more for stable values in the tails.

seed

A seed for the shuffles, so the residuals repeat exactly. The session's own random stream is left as it was. Default NULL. Ignored with residuals = "asymptotic".

values

Whether to print each tile's residual (one decimal) inside it. Default FALSE. In the classic style the text is white on strongly coloured tiles (absolute residual above 1.5) and dark grey otherwise; with style = "flat" it is white on tiles whose absolute residual exceeds 0.55 of the largest, and tiles too small for a label stay blank.

style

"classic" (default) draws black-bordered tiles with axis labels. "flat" draws the mosaic of mosaic_analysis(): white gutters between tiles, labels beside them, no axes, and a ColorBrewer red-blue residual ramp; values = TRUE then prints the residuals in the tiles, and its styling arguments (tile_label, col_label_side, row_label_side, legend_position, legend_size, label_size, ...) go in .... An mcml with level = "clusters" and more than one panel is drawn classic, with a message; an htna drawn flat loses its actor-coloured labels, with a warning.

nested

Whether the counts are nested in actors (transitions in sequences, sequences in students or teams) and the residuals should allow for it. Default FALSE: every count is an independent draw, as before. TRUE draws the residuals of nested_method; see Nested data.

nested_method

With nested = TRUE, the method: "rao_scott" (default), "donner_klar", "cmh", "gee" or "glmm"; see Nested data. A method that cannot run on the design raises an error of class nestimate_bad_input.

actor

With nested = TRUE, on a network or netobject_group: NULL (default) makes every sequence its own actor; the name of a column of the network's metadata (such as "Actor" or a team column, as actor in permutation() and bootstrap_network()) pools the sequences that share its value; several names give nested levels, outermost first, which "glmm" models level by level and the other methods reduce to the outermost. A name that is not a column raises an error of class nestimate_actor_missing. nested_method and actor given with nested = FALSE are ignored with a warning of class nestimate_ignored_argument.

report

Whether to report the overall test: TRUE adds it as the plot subtitle and prints it as a one-row data frame with the columns of mosaic_test() but note. The test is nested_method with nested = TRUE, Pearson's chi-square otherwise. Default FALSE. Not available for an mcml.

level

For an mcml: "macro" (default) draws one mosaic of the cluster-by-cluster counts; "clusters" draws one mosaic per cluster, as panels of one plot that share the residual scale.

ncol

For an mcml with level = "clusters": the number of panel columns. Default 2. Accepted by the netobject_group method, whose single mosaic does not use it.

x_var, y_var, weight

For a data frame: the column whose levels form the mosaic's columns (each as wide as its total weight), the column whose levels are stacked within each column (in proportion to their share), and the column holding each row's weight, such as a count. Levels keep their factor order, or sort alphabetically. x_var, y_var, weight, fill, colors and show_labels given with any other input raise an error of class nestimate_bad_input, as does label_size outside style = "flat".

fill

For a data frame: "y" (default) colours the segments by y_var; the name of another column maps that column to the fill instead (the first value per cell).

colors

For a data frame with fill = "y": fill colours, either an unnamed vector in level order (at least one per level) or a named lookup such as c(plan = "#0072B2") that overrides only the levels named. Default NULL, the Okabe-Ito palette, recycled.

show_labels, label_size

For a data frame: whether to print each segment's percentage inside it (default TRUE; segments under 4% stay unlabelled), and the label size (default 3.5). With style = "flat", label_size also sizes the flat mosaic's tile labels.

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 a netobject_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_group raises 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 netobject or htna network (relative or frequency, with its sequences), a netobject_group, a three-way table or array (rows x columns x actors), or a data frame (with var1, var2 and actor). A co-occurrence network raises an error of class nestimate_mosaic_undirected: it counts each pair of states in both mirrored cells and the pairs of a sequence share its positions, so its counts are not independent and the tests would not hold their level (under independence Pearson's test rejected 200 of 200 simulated tables at 0.05). mosaic_plot() still draws it. A tna model or a group_tna (package tna) is first rebuilt as a network from its own sequences (see as_netobject()). 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.

...

Not used; a name given here raises an error of class nestimate_bad_input.

method

The tests to run, any of "chisq", "rao_scott", "donner_klar", "cmh", "gee" and "glmm". Default: all six.

actor

The actor column(s), as in permutation(): for a network or netobject_group, NULL (default) makes every sequence its own actor, and the name of a metadata column (such as a team) pools the sequences that share its value; for a data frame, the column(s) that identify the actors (required). Several names give nested levels, outermost first: "glmm" models each level, the other tests use the outermost. Not used for a three-way table, whose third dimension is the actor.

level

"test" (default) for one row per test, "cells" for one row per cell per test with the cell's residual.

var1, var2

For a data frame: the names of the two variables; var1 is the predictor.

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 data1 in the same order; columns that differ in name or order raise an error of class nestimate_bad_input. An unnamed matrix is matched by position and takes the other group's names, or V1, V2, ... when neither group has names.

iter

The number of permutations, a whole number of at least 1. Default 1000.

gamma

The EBIC tuning parameter of the glasso, a non-negative number; larger values give sparser networks. Default 0.5.

paired

Whether row i of both groups is the same unit (such as a person measured twice). Each permutation then swaps the two rows of a unit at random instead of shuffling all rows, and the groups need the same number of rows, otherwise an error of class nestimate_bad_input is raised. Default FALSE.

abs

Whether global strength sums the absolute edge weights. With FALSE, it sums the signed weights (global expected influence). Default TRUE.

weighted

Whether the tests compare the weighted networks. With FALSE, both networks are binarised (an edge is present or absent) before the statistics are computed. Default TRUE.

p_adjust

The multiplicity correction for the per-edge p-values, any method of stats::p.adjust(). Default "none".

na_method

How missing values are handled. "pairwise" (default) keeps every row, permutes rows as usual, and estimates each sample or permuted split from its pairwise-complete correlation matrix, with the median pairwise co-observation count as the sample size; a variable pair sharing fewer than two observed rows there raises an error of class nestimate_degenerate_sample. "listwise" drops incomplete rows first (with paired = TRUE, a pair is dropped when either member is incomplete). Complete data are unaffected by the choice.

x

For the print() and as.data.frame() methods: a net_nct object.

n

For the print() method: the number of edges to list, largest difference first. Default 6; Inf lists them all, as does summary(x, table = "edges").

...

For the print(), summary() and as.data.frame() methods: ignored.

object

For the summary() method: a net_nct object.

table

For the summary() method: "tests" (default), the global tests, or "edges", one row per node pair (the table described below).

row.names, optional

For the as.data.frame() method: ignored, kept for compatibility with the base generic.

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) and p_value.

strength

The global-strength test (statistic S): the same, plus by_group, each network's global strength (NCT's glstrinv.sep).

E

The per-edge tests: observed and p_value hold one value per node pair (the upper triangle), perm is an iter by node-pair matrix, and edge_names is a data frame with the columns from and to naming 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_adjust and na_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. NA is allowed and removed with the zeros; an infinite value raises an error.

method

How to combine the weights: "sum" (default), "mean", "median", "max", "min", "prod", "density" or "geomean". A single value; any other raises an error. "density" divides the sum by n_possible, and "mean" by the number of non-zero weights, so the two agree when every possible edge is present, and "density" is the smaller when some are zero or missing. "geomean" is the geometric mean of the positive weights; negative weights are left out, and the result is 0 when none is positive.

n_possible

For method = "density": the number of possible edges, such as the block size n_i * n_j of two clusters, a single finite number. Default NULL, under which (as with a value of 0 or less) "density" returns the mean of the non-zero weights. Other methods ignore it.

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 netobject, netobject_group, mcml or cograph_network. A tna model or a group_tna (package tna) is first rebuilt as a network from its own sequences (see as_netobject()). For the plot() methods: the result of net_centrality().

measures

The measures to compute. The default is "InStrength", "Betweenness" and "Diffusion"; "all" computes every built-in one: "OutStrength" and "InStrength" (sum of outgoing or incoming weights), "ClosenessOut", "ClosenessIn" and "Closeness" (inverse of the summed shortest-path distances from, to, or ignoring the direction of edges), "Betweenness" (how many shortest paths pass through the node), "BetweennessRSP" (betweenness over randomised shortest paths, which also counts near-shortest routes), "Diffusion" (the summed weights of walks of length 1 to n from the node) and "Clustering" (weighted clustering coefficient). "InCloseness" and "OutCloseness" are accepted for "ClosenessIn" and "ClosenessOut". With centrality_fn, name its measures here to have them returned.

loops

Whether self-loops (staying in a state) count. With FALSE (default) they are left out of every measure, and a message says so.

normalize

Whether to range-normalise every measure to 0–1, as tna::centralities(normalize = TRUE) does. Default FALSE.

invert

Whether a heavier edge is a shorter step in the shortest-path measures (distance = 1 / weight), as in tna. With FALSE, the weight itself is the distance. Default TRUE.

normalize_diffusion

Whether to range-normalise Diffusion even when normalize = FALSE. Default TRUE.

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 measures. Default NULL.

format

For a netobject_group or an mcml: "long" (default), one row per network and node, or "wide", one row per node with a ⁠<measure>_<network>⁠ column per measure and network. Ignored for a single network.

...

Not used.

n

For print(): the number of rows shown. Default 20.

digits

For print(): the decimals shown. Default 2.

object

For summary(): a net_centrality or net_centrality_group result.

i, j

For [: rows and columns, as for a data frame. A subset of a centrality result is a plain data frame.

reorder

For the plot() methods: whether to sort the nodes in each measure's panel by their value (for a group, by their mean value across networks). Default TRUE.

ncol

For the plot() methods: the number of panel columns. Default 3.

type

For the plot() methods: the kind of plot. "bar" (default) draws one panel of bars per measure, grouped bars for several networks. "line" draws each node's profile across the measures (for several networks, one panel per node and one line per network); "profile" is accepted for it. A single network also takes "heatmap", a nodes-by-measures grid with each measure scaled to 0–1 for the colour and its raw value printed in the tile. Several networks also take "delta", bars of the differences between networks: the second minus the first with two, each network's deviation from the per-node mean with more.

scales

For the plot() methods: "free_x" (default) gives each measure its own value axis, "fixed" one shared axis.

profile_scale

For type = "line": "measure" (default) rescales each measure to 0–1 so the profiles compare across measures; "none" draws raw values.

labels

For the plot() methods: whether to print the values on the plot. Default TRUE for one network, FALSE for several.

drop_zero

For the plot() methods: whether to leave out measures that are zero for every node. Default FALSE.

palette

For plot() of several networks: the ColorBrewer palette for the networks. Default "Set2". Ignored by type = "delta" with two networks, whose bars are coloured by which network is higher.

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 netobject or netobject_group. A network that was never pruned, or whose pruning is already inactive, raises an error, and so does another class.

...

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

net_prune, net_reprune

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 netobject or netobject_group. A tna model or a group_tna (package tna) is first rebuilt as a network from its own sequences (see as_netobject()). Any other input raises an error. For the plot() method: a net_edge_betweenness network.

invert

Whether to turn weights into distances by 1 / weight before finding shortest paths, which suits probability and frequency networks. With FALSE, the weight itself is the distance; use it when the weights already are distances. Default TRUE.

...

Not used.

style

For the plot() method: the kind of chart. "bar" (default) draws one horizontal bar per edge; "forest" a stem from zero to a point, with a dashed line at the mean betweenness of the edges shown; "delta" each edge's deviation from that mean as a bar pointing right (above the mean, blue) or left (below, red).

top_n

For the plot() method: the number of highest edges to keep. Default NULL (every edge with non-zero betweenness).

labels

For the plot() method: whether to print each edge's value (its deviation, for "delta") beside it. Default TRUE.

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 netobject or a netobject_group. A tna model or a group_tna (package tna) is first rebuilt as a network from its own sequences (see as_netobject()). Another class raises an error. A network whose pruning is active raises an error of class nestimate_bad_input; after net_deprune() it can be pruned again with other settings, which replaces its pruning record.

method

The pruning method: "threshold" (default), "lowest", "disparity" or "bootstrap" (see Methods).

threshold

For method = "threshold": the largest weight that is removed. Default 0.1. Ignored by the other methods, but must still be a single number.

lowest

For method = "lowest": the quantile, between 0 and 1, of the positive weights that sets the cut-off. Default 0.05. Ignored by the other methods, but checked whatever the method: a value outside ⁠[0, 1]⁠ raises an error.

level

For method = "disparity": the significance level, between 0 and 1; an edge is kept when its p-value is below it. Default 0.5. Ignored by the other methods, but checked whatever the method: a value outside ⁠[0, 1]⁠ raises an error.

boot

For method = "bootstrap": a net_bootstrap from bootstrap_network() of this network. With the default NULL, the bootstrap is run here on x. For a netobject_group, pass the net_bootstrap_group of bootstrap_network() on the group, matched to the networks by name, or NULL to bootstrap each network on its own. Another object, a bootstrap of another network (its weights or its data differ), a single net_bootstrap for a group, or a group bootstrap missing one of the networks raises an error of class nestimate_bad_input.

...

Arguments for bootstrap_network(), such as iter, when method = "bootstrap" and boot = NULL; ignored otherwise.

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 lowest quantile 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 level against 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 as boot, 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 netobject or netobject_group; a network that was never pruned, or another class, raises an error. For the print() method: a net_pruning_details.

...

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

net_prune

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 netobject or netobject_group. A network that was never pruned, or whose pruning is already active, raises an error, and so does another class.

...

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

net_prune, net_deprune

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 netobjects from build_network(). A netobject_group is split into its networks, named by group; an mcml is converted with as_tna() first, and a bare cograph_network is read as a netobject. Each network is named by its argument name or, failing that, its method; repeated names get a suffix ("_1", "_2", ...). A tna model or a group_tna (package tna) is first rebuilt as a network from its own sequences (see as_netobject()). A network without its sequence data (which build_network() keeps) raises an error, a network resting on one sequence an error of class nestimate_single_sequence, a sequence network with no observed transition an error of class nestimate_no_transition, a network built with level an error of class nestimate_multilevel_resampling, a network built with method = "latency" an error of class nestimate_latency_resampling, and networks of different methods with scale = "none" a warning of class nestimate_mixed_methods. For the print(), summary() and plot() methods: ignored.

iter

The number of split-half iterations, at least 2. Default 1000.

split

The share of the sequences that goes to the first half, the rest forming the second, strictly between 0 and 1. Default 0.5.

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: "none" (default); "minmax", which maps each matrix to 0–1; "standardize", which subtracts the mean of its cells and divides by their SD; or "proportion", which divides by the sum of its cells. A matrix whose cells are all equal, or sum to 0, is left as it is.

seed

A seed for the random splits, so the result repeats exactly. The session's own random stream is left as it was. Default NULL.

x

For the print() and plot() methods: a net_reliability object.

object

For the summary() method: a net_reliability object.

bins

For the plot() method: the number of histogram bins per panel. Default 60.

combined

For the plot() method: TRUE (default) draws the four metrics as panels of one plot; FALSE returns a named list of four single-panel plots, one per metric, without drawing them.

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, cor and max_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

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 adjust covariate or the group column are left out; when none is left, an error of class nestimate_empty_model_frame is raised. A column that is not in data raises an error.

outcome

The outcome column. With family = "auto", an outcome with two distinct values is modelled with the binomial family (the second value in sort order, level order for a factor, or TRUE, coded 1) and any other with the gaussian family, which needs a numeric outcome.

predictors

The predictor columns. A predictor that is not numeric (a logical column included; convert it with as.integer()) or has no variance in the complete rows is dropped and listed in the result; when every predictor is dropped, an error of class nestimate_no_variance is raised.

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 nestimate_no_lme4 is raised, and a plain stats::glm() is fitted. Default NULL.

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

family

The model family: "auto" (default) reads it from the outcome, "binomial" and "gaussian" force one. "binomial" codes the second-smallest outcome value (or TRUE) as 1 and every other value as 0, so give it a two-valued outcome.

select

How the predictors are chosen: "none" (default) fits all of them; "split" ranks them on a random half of the rows (with a group, the rows of a random half of the groups) by the absolute z or t statistic of a one-predictor glm() (without adjust or group), keeps the best n_select, and fits the reported model on the other half. With a group, fewer than two groups in the complete rows raise an error of class nestimate_bad_input.

n_select

The number of predictors kept when select = "split". Default 10. Ignored otherwise.

correction

The multiplicity correction, any method of p.adjust(). Default "BH".

ci_level

The confidence level of the intervals, between 0 and 1. Default 0.95.

seed

An integer that makes the split reproducible; used only with select = "split". A random-number state that existed before the call is restored afterwards. Default NULL.

x

For the print() and plot() methods: an outcome_model() result.

...

For the print(), summary() and plot() methods: not used.

object

For summary(): an outcome_model() result.

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 adjust covariates included, and columns term, estimate, std_error, statistic, ci_lower, ci_upper, p_value and p_adj (NA on the intercept row, which is left out of the correction), plus odds_ratio, or_lower and or_upper for 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; NA unless 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 netobject, bare cograph_network or tna model with non-negative transition weights, typically method "relative" or "frequency" (a co-occurrence network is read as its random walk), a non-negative numeric transition matrix (states are named S1, S2, ... when it has no names), or a wide sequence data frame or character matrix, from which a "relative" network is estimated. A data frame needs its position columns named as a numbered run, as in build_network(); build the network first for any other layout. A netobject_group gives one result per group. An association network (cor, pcor, glasso, ising, mgm) or negative weights raise an error of class nestimate_not_markov. For the print() and plot() methods: a net_mpt or net_mpt_group.

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 NULL (all states).

normalize

Whether to rescale rows that do not sum to 1 so that they do, with a warning, as for a "frequency" network. With FALSE, such rows raise an error. A state with no outgoing transitions (a zero row) raises an error either way. Default TRUE.

digits

Decimal places of the printed matrix (print()) and of the tile labels (plot()). The stationary distribution is always printed with 4. Default 1.

...

For print() of a net_mpt_group: passed to print() of each group's result (for example digits). Otherwise not used.

object

For the summary() method: a net_mpt.

table

For summary(): "states" (default), one row per state (state, return_time, stationary, mean_out, mean_in), or "pairs", one row per ordered pair of states (from, to, passage_time, the mean number of steps from from to first reach to; for from equal to to, the mean return time).

log_scale

For the plot() methods: whether to colour the tiles by the logarithm of the passage time, so that short and long times can both be told apart; the legend and the tile labels still show steps. Default TRUE.

title

For the plot() methods: the plot title. Default "Mean First Passage Times".

low, high

For the plot() methods: the fill colours for the shortest and the longest passage times. Default "#004d00" (dark green) and "#ccffcc" (pale green).

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 n matrix of mean first passage times: row i, column j is the expected number of steps from state i to state j; the diagonal is the mean recurrence time, equal to 1/\pi_i on an irreducible chain.

stationary

The stationary distribution \pi, a named numeric vector; zero outside the closed class of a chain with one closed class, and NA for 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_i in an irreducible chain, Inf for 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 tna model or a netobject built from sequences. A data frame needs position columns named as a numbered run (T1, T2, ...); any other frame, a one-hot or association network and a 0/1 matrix raise an error of class nestimate_bad_input. A missing value ends a run of observed states, and no path spans it.

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 2, which counts single transitions; 3 counts two-step paths, and so on.

top

The number of most frequent paths to keep. Default NULL, every path.

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 netobject built from sequences, whose stored data are read. A data frame needs position columns named as a numbered run (T1, T2, ...); any other frame, a one-hot network and an association network raise an error of class nestimate_bad_input, and a network without its data stops path_dependence(). Paths that touch a missing cell are left out. A tna model (package tna) or a bare cograph_network gives the sequences it carries. For the print() methods: a net_path_dependence object or its summary(); for the plot() method: a net_path_dependence object.

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 2, which compares a two-state history with the last state alone; 3 compares a three-state history, and so on. The data need at least order + 1 time steps.

min_count

The number of times a context must be observed to be reported, a whole number of at least 1. Default 5. Contexts seen less often give noisy KL estimates; when no context reaches min_count, path_dependence() stops with an error of class nestimate_bad_input.

base

The logarithm base for the entropies and the KL divergence: 2 (default) gives bits, exp(1) nats and 10 hartleys. A positive number other than 1.

top

For the print() and plot() methods: how many contexts to show, highest KL first. Default 10 for print() and 15 for plot().

digits

For the print() methods: decimal places of the entropies, the entropy drop and the KL, in the table and in the chain-level summaries. Default 3.

...

For the print(), summary() and plot() methods: ignored.

object

For the summary() method: a net_path_dependence object.

title

For the plot() method: the plot title. Default NULL, which builds "Path dependence: order k vs order 1" from the fitted order.

Details

For each context c observed at least min_count times, the function computes:

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 of P_1(\cdot \mid s_k)), H_orderk (entropy of P_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) and flips (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_contexts and n_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:

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 netobject of an association method, or a one-hot one, raises nestimate_bad_input; a network without its sequences stops pathways().

...

For the netobject method: passed to the pathways() method of the HON or HYPA built from it, so min_count, min_prob, top and order apply to a HON and type to a HYPA. Ignored by the other methods.

min_count

For a HON or a MOGen: the smallest transition count kept, which filters out rare observations. Default 1 (all).

min_prob

For a HON or a MOGen: the smallest transition probability kept. Default 0 (all).

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 NULL (all), except for link predictions, whose default is 10. Not used for a HYPA.

order

For a HON: keep only pathways whose source has this order. Default NULL, every order above 1; order 1 returns nothing. For a MOGen: the Markov order to extract. Default NULL, the optimal order from model selection; an order below 1 returns character(0).

type

For a HYPA: which anomalies to include, "all" (default), "over" (over-represented paths) or "under" (under-represented ones).

ho_method

For a netobject: the higher-order model built from its sequences, "hon" (default, build_hon()) or "hypa" (build_hypa()), each with its default settings. The network must carry the sequences it was built from.

min_lift

For association rules: the smallest lift kept, on top of the threshold the rules were mined with. Default NULL (no further filter).

min_confidence

For association rules: the smallest confidence kept, on top of the mining threshold. Default NULL (no further filter).

method

For link predictions: the prediction method whose links are returned. Default NULL, the first method in the object. A method the object does not hold returns character(0).

evidence

For link predictions: whether to extend each predicted link A -> B with its common neighbours, the nodes with an edge from A and an edge to B, giving "A cn1 cn2 -> B". Default TRUE. Without a stored adjacency matrix the links are returned as "A -> B".

max_evidence

For link predictions with evidence = TRUE: the most common neighbours added to one link; when there are more, those with the largest summed weight of the edges from A and to B are kept. Default 3.

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)

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 extract_sequences() accepts: prepared data, a long event log, a wide data frame, a netobject, netobject_group or tna model.

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 tna model. The default, "last_obs", uses each sequence's last observed state as the outcome and removes the states that end some sequence from all sequences, as codyna does; it suits data whose final state codes the outcome, such as an appended "pass" or "fail". An outcome without exactly two values, a vector of the wrong length or a column that is not stored with the sequences raises an error of class nestimate_bad_input.

type, len, gap, min_freq, min_support, start, end, contain

The pattern definition and filters; see sequence_patterns(). The defaults are codyna's: type = "ngram", len = 1:2, gap = 1, min_freq = 5 and min_support = 0.01. When no pattern passes the filters under both outcome values, an error of class nestimate_no_patterns is raised.

n

The number of patterns entered into the model, a positive whole number. Default 10.

priority

The columns ranking the patterns for selection, applied in order: "chisq" (default), "p_value", "support", "n_sequences", "occurrences", "proportion", "lift" and "length".

desc

Whether each priority column ranks in descending order, recycled to the length of priority. Default TRUE, so "p_value" needs desc = FALSE to select the smallest p-values.

occurrences

Whether each pattern enters the model as its number of occurrences in the sequence instead of its presence (0/1). Default FALSE.

adjust

Covariate columns added to the model. Default NULL. A name that is not a column stored with the sequences raises an error of class nestimate_bad_input.

adjust_length

Whether to add the number of observed states per sequence as a covariate. Default FALSE, as in codyna.

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 nestimate_no_lme4 is raised. Default NULL. A name that is not a column stored with the sequences raises an error of class nestimate_bad_input.

reference

The reference outcome value; the odds ratios are for the other value. Default NULL, the first value in sorted order; a value that does not occur raises an error of class nestimate_bad_input.

ci_level

The confidence level of the Wald intervals, a number between 0 and 1. Default 0.95.

cols

The state columns of a wide data frame; see extract_sequences(). Default NULL.

actor, action, time

The actor, action and timestamp columns of a long event log; setting action marks x as one. Default NULL.

...

Further arguments passed to prepare() for a long event log, such as time_threshold or order.

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:

  1. Patterns are found as in sequence_patterns() and filtered by min_freq, min_support, start, end and contain. Patterns absent from all sequences of one outcome value are dropped.

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

  3. The top n patterns by priority enter one model, outcome ~ adjust + pattern_1 + ... + pattern_n, as presence indicators (or occurrence counts with occurrences = TRUE). Ties keep codyna's order: more occurrences first, then first appearance. With group, a random intercept per group is added (lme4::glmer()); otherwise the model is a plain glm().

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

sequence_patterns

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:

  • a netobject from build_network(), or a bare cograph_network;

  • a netobject_group, an mcml or a wtna_mixed;

  • a net_edge_betweenness() result;

  • a tna model or group_tna, rebuilt as a network from its own sequences (see as_netobject()). Raises nestimate_actor_missing when actor is given and the model keeps no metadata; models built with tna::prepare_data() keep it.

For the print() methods: a permutation() result.

y

The second network, of the same kind as x, estimated with the same method on the same nodes (their order may differ); other methods or nodes raise an error. Default NULL: when x is a netobject_group or an mcml, every pair of its groups is tested. When both are netobject_groups, the groups present in both under the same name are tested, and having none in common raises an error.

iter

The number of shuffles, at least 2. Default 1000. The smallest attainable p-value is 1 / (iter + 1).

alpha

The significance level, strictly between 0 and 1, that marks an edge or centrality as significant (sig, diff_sig) and that the nestimate_few_actors warning is checked against. It does not change the p-values. Default 0.05.

paired

Whether the two networks hold paired observations (the i-th sequence or row of x with the i-th of y, such as the same people measured twice; for one-hot data, the i-th actor in the order the actors first appear). Each shuffle then swaps the two members of a pair at random instead of shuffling all labels, so x and y need the same number of sequences (after concat) or rows; otherwise an error is raised. It cannot be combined with actor, of which it is the special case of one actor per pair. Default FALSE.

adjust

The multiplicity correction for the p-values, a method of stats::p.adjust(): "none" (default), "holm", "hochberg", "hommel", "bonferroni", "BH", "BY" or "fdr". The correction runs over the tested edges: the cells non-zero in either network (a self-loop included), each pair counted once in an undirected network, whose matrix stays symmetric. Cells zero in both networks keep their raw p-value, 1. The centrality p-values are corrected separately, over all states and measures. Any other value raises an error of class nestimate_bad_input before anything runs.

measures

Centrality measures to test as well as the edges: any of "OutStrength", "InStrength", "ClosenessIn", "ClosenessOut", "Closeness", "Betweenness", "BetweennessRSP", "Diffusion" and "Clustering" ("InCloseness" and "OutCloseness" are accepted for "ClosenessIn" and "ClosenessOut"), or "all" for the nine. Default NULL (edges only). Every state and measure gets the observed difference, an effect size and a p-value from the same shuffled networks as the edge test. The centralities are computed as by net_centrality() with its defaults: self-loops left out, heavier edges as shorter steps, and Diffusion range-normalised to 0–1 in each network. An unknown name raises an error, and so does any measures with net_edge_betweenness() input.

nlambda

Ignored, kept so existing calls run. Default NULL. The shuffled glasso networks use the nlambda the networks were built with (see Details); a value other than NULL gives a warning of class nestimate_ignored_argument.

seed

An integer that makes the shuffles reproducible. Default NULL. The session's own random stream is left as it was; with grouped input each pair, or each shared group, is tested from the same seed.

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 "student_id" when sessions are nested in students, or "Group" for students nested in teams) and then in its wide sequence data. Whole actors are then shuffled, and the ICC and design effect are reported; see the sections Nested data and actor and ICC and design effect. Several column names, outermost first, are nested levels (such as c("Group", "Student")): labels are shuffled at the level where they are assigned, within the units above it. Default NULL: sequences are shuffled one by one. Raises nestimate_actor_missing when the column is absent or incomplete, and nestimate_actor_misaligned when it does not give one actor per sequence.

...

For the print() and summary() methods: not used.

object

For the summary() methods: a net_permutation, net_permutation_group or wtna_perm_mixed.

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 adjust is 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 columns from, to, weight_x, weight_y, diff, effect_size, p_value and sig.

global

The global test, one row per statistic: statistic ("M", the sum of absolute differences, and "S", the largest absolute difference), observed, and p_value from 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 invert setting and the source method used.

iter, alpha, paired, adjust

The settings used.

actor

The actor column name (or names, outermost first), or NULL.

n_actors

The number of distinct actors (with several levels, at the innermost level), or NULL.

actor_levels

Only with several actor levels: one row per level, with level (the column), n_actors (the units at that level), n_pure and n_crossed (the units the shuffle met at that level, inside crossed units of the level above, that sit in one group or in both) and design ("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 with n_sequences, n_actors, design ("between", "within" or "mixed"; with several levels, one "<level>: <design> (<n> actors)" entry per level), icc (at the innermost level) with icc_ci_lower and icc_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) and min_p, the smallest p-value the exact test over the actors' arrangements can give: one over their number, or 1 / (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, with from, to, icc, null_sd_actor, null_sd_sequence and deff.

centralities

Only with measures: a list of stats (one row per state and measure, with state, centrality, diff_true, effect_size and p_value), diffs_true (the observed differences, one row per state and one column per measure) and diffs_sig (the same where p < 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 actor levels it is computed at the innermost level (the finest actor, such as the student within a team), and print() 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 netobject_group, whose every pair of groups is diagnosed, or a netobject, compared with y. An mcml, whose layers hold different states, raises an error of class nestimate_bad_input. Only the transition methods "relative", "frequency" and "co_occurrence" are supported; any other method raises nestimate_actor_unsupported, and a latency network, which is not resampled, raises nestimate_latency_resampling. A tna model or group_tna must keep its metadata, as one built with tna::prepare_data() does.

y

The netobject to compare with when x is a netobject. Default NULL, as it must stay when x is a group.

actor

The column identifying the actor each sequence belongs to, as in permutation(), looked up in the networks' metadata or sequence data. Several column names, outermost first (c("Group", "Student")), are nested levels, shuffled as permutation() describes; the ICC is then that of the innermost level. A column not found, or one with missing values, raises an error of class nestimate_actor_missing. Required.

iter

The number of permutations for each of the two tests, at least 2. Default 1000.

alpha

The significance level that counts an edge as significant, between 0 and 1. The p-values are not adjusted for multiplicity. Default 0.05.

level

"overall" (default) returns one row per compared pair; "edges" one row per edge per pair.

seed

A seed for the shuffles, used by both tests, so the result repeats exactly. Default NULL.

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 several actor levels, 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 is NA; the ICC is NA when 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 M statistic.

p_global_sequence, p_global_actor

The permutation p-values of M when sequences or whole actors are reassigned.

sig_edges_sequence, sig_edges_actor

The number of edges with p < alpha under 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_actor and 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_global

The 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_changed

Edges significant under one test but not the other. Edges with p-values close to alpha can flip from Monte Carlo error alone; increase iter before reading much into one or two.

min_p_actor above alpha

Too few actors: the exact actor-level test cannot reject anything, and an actor-level p-value below alpha is 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

permutation

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 persistent_homology() result, or a data frame with the columns dimension, birth and death.

k_max

The number of landscape functions to compute, a positive whole number. Functions beyond the number of pairs are zero. Default 5.

dimension

The homology dimension, a single non-negative whole number. Default 1.

t_grid

The filtration values to evaluate the landscape at. Default NULL: 200 evenly spaced points from the smallest birth to the largest death of the remaining pairs (each pair is ordered so that birth comes first, since clique filtrations descend), or from 0 to 1 when no pair remains. Pass the same grid to landscapes you want to compare.

x

For the print() and plot() methods: a persistence_landscape object.

...

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, t and value.

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_scale caps 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 type = "clique", non-negative distances for type = "vr"), a tna model, a netobject or cograph_network (a net_hon among them), or a simplicial_complex from build_simplicial(type = "vr"). The complex's stored entry values are reduced as they are, so its own type is used and type is ignored; a complex without them (a clique or pathway complex) raises an error. A complex built with a max_dim below its largest clique warns with class nestimate_truncated_complex, since its top-dimension features cannot die, when the complex's dimension is at most max_dim and the truncated part lies within max_scale. All-zero weights raise an error in the clique filtration, and negative distances in the Vietoris-Rips one. So does a Vietoris-Rips input in which no edge can enter: every off-diagonal distance missing or infinite, or max_scale = 0 with all distances positive. An all-zero distance matrix gives a single component, and distances that all exceed max_scale give one essential component per node. For the print() and plot() methods: a persistent_homology object.

n_steps

The number of thresholds on which the Betti curve is reported, a positive whole number. Default 20. The persistence diagram does not depend on it.

max_dim

The highest feature dimension reported, a non-negative whole number. Default 3. A simplicial_complex input supplies only the simplices it holds.

type

The filtration: "clique" (default), on similarity weights, or "vr" (Vietoris-Rips), on distances.

max_scale

For type = "vr", and for a Vietoris-Rips simplicial_complex: the largest distance at which an edge enters; longer edges and the simplices that hold them are left out. Default NULL, the largest finite distance (for a complex, every simplex it holds).

...

For the print() and plot() methods: ignored.

combined

For the plot() method: TRUE (default) draws the Betti curve and the persistence diagram side by side, which needs gridExtra; FALSE returns them as a named list of ggplots (betti_curve, persistence).

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, dimension and betti, the number of features alive at that threshold.

persistence

Data frame with one row per feature, sorted by decreasing persistence: dimension, birth, death and persistence. Essential features are included, with death = 0 in the clique filtration and death = Inf in 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 netobject, netobject_group, mcml or htna network built from sequences. A tna model or a group_tna (package tna) is first rebuilt as a network from its own sequences (see as_netobject()). A network without sequence data raises an error; in a netobject_group or mcml, groups without it are left out. For the print() and plot() methods of the result: the state_freq object; for the print() methods of a per-panel figure: an object of class nestimate_facet_plot or nestimate_facet_list.

...

Not used: the netobject, netobject_group and htna methods ignore an argument they do not take with a warning of class nestimate_ignored_argument; the mcml method raises an error for it. For the print() and plot() methods of the result: ignored.

style

The chart. "marimekko" (default) draws treemaps, or the cluster marimekko for an mcml (see Description); "bars" draws horizontal bars, the most frequent state on top when sort_states = "frequency", with one panel per group.

metric

For style = "bars": what the bar length shows, "prop" (default), the share within the group, or "freq", the count. Treemap and marimekko areas always show the share within the group.

label

The text printed on each tile or bar, on one line: "prop" (default) the share, as in "66.0%"; "freq" the count, as in "1,234"; "both" the two, "1,234 (66.0%)"; "state" the state name; "all" the name and share, "Average (66.0%)"; "none" no text.

legend

Where the colour legend goes: "bottom", "top", "right", "left", "none" or "per_facet". "auto" (default) resolves to "none" for bars, whose axis names the states, to "per_facet" for htna and mcml treemaps, and to "bottom" otherwise. "per_facet" draws each group as its own treemap with its own legend (on the right with up to two panels, at the bottom with more), and its colours restart in every panel; it falls back to "bottom" when every group has the same states, and to a legend on the right for bars. It returns a combined figure or a list of plots, as combine sets.

legend_dir

The direction of the legend's keys: "auto" (default) lays them out horizontally for a legend on top or bottom and vertically on the left or right; "horizontal" and "vertical" force one.

legend_frame

"none" (default) draws the legend unframed; "border" draws a thin grey rectangle around it.

sort_states

The order of the states in the legend, the tiles and the bars: "frequency" (default), the most frequent first; "alpha", alphabetical; or "none", the order of the table.

colors

Deprecated name of state_colors; it still works, with a warning of class nestimate_deprecated.

label_size

The size of the tile and bar labels; with ggfittext installed, the largest size, as labels shrink to fit their tiles. Default 3.5.

abbreviate

Whether to shorten the state names with base::abbreviate(), which drops lower-case vowels and then letters from the end until a name fits, keeping the names distinct. FALSE (default) keeps the full names; TRUE shortens them to at least three characters; a positive whole number sets that minimum length. It applies to the labels, the legend and the returned table.

include_macro

For an mcml: whether to add a "macro" group in front, holding the state counts over all clusters. Default FALSE. Ignored for the other classes.

combine

With per-panel legends: "auto" (default) combines up to three panels into one figure and returns a list of plots, one per panel, for four or more, which knitr draws as separate figures at the chunk's size. TRUE always combines them; FALSE always returns the list. A combined figure, whether from TRUE or from "auto" with up to three panels, needs gridExtra and raises an error without it; FALSE does not.

ncol

For a combined figure with per-panel legends: the number of columns. Default NULL: one column per panel with up to two panels, two columns with more.

node_groups

A named character vector that maps states to broader groups, such as c(plan = "Regulation", monitor = "Regulation"). The chart is then drawn and coloured by these groups, states not named keeping their own name; the returned table keeps one row per state. Default NULL.

state_colors

Fill colours for the states, overriding the palette attached to x with set_state_colors() for this chart: an unnamed vector in state order (at least one per state) or a named lookup such as c(plan = "#0072B2") that overrides only the states named. Default NULL: the attached palette, or else Okabe-Ito, as every figure of x draws them.

digits

For print() of the result: decimal places of the percentages. Default 1.

max_states

For print() of the result: the most states shown per group (default 20); the rest are folded into one "(+k more)" row. state_distribution() gives the full table.

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))
}

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 netobject, a cograph_network, a tna model, or a numeric square weight matrix. A network keeps its own direction; a matrix or tna model is directed unless it is symmetric. A netobject_group or an mcml raises an error of class nestimate_bad_input: predict each network separately. For the print() method: a predict_links() result.

methods

The indices to compute, one or more of "common_neighbors", "resource_allocation", "adamic_adar", "jaccard", "preferential_attachment" and "katz" (defined under Details). By default all six.

weighted

Whether common neighbours, resource allocation, Adamic-Adar and Jaccard use the edge weights (TRUE, default) or the binary adjacency (FALSE). Preferential attachment, Katz and the degrees that resource allocation and Adamic-Adar divide by always use the binary adjacency.

top_n

The number of predictions kept per index, the highest scores. Default NULL (every pair). The ranks are computed before the cut, so they stay the same.

exclude_existing

Whether pairs that already have an edge are left out of the predictions. Default TRUE.

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

katz_damping

The attenuation factor \beta of the Katz index. Default NULL, which uses 0.9 / \rho(A) for the spectral radius \rho(A) of the adjacency (0.1 when it is 0). A value at or above 1 / \rho(A), where the series diverges, is replaced by 0.9 / \rho(A) with a warning of class nestimate_ignored_argument. If the closed form cannot be solved, the scores are the first six terms of the series and a warning of class nestimate_no_converge says so.

...

For the print() and summary() methods: not used.

object

For summary(): a predict_links() result.

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 = TRUE it 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) and rank (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) and consensus_rank (shared by equal avg_ranks), ordered by avg_rank. NULL when 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 netobject estimated with method = "glasso", "pcor" or "cor", or a netobject_ml or netobject_group of them. A tna model, group_tna or bare cograph_network is read as the network it holds. A network from any other method, and any other object, raises an error of class nestimate_bad_input.

...

Not used.

data

The variables the network was estimated from, used only for the RMSE column; R^2 comes from the matrices stored on the network. Its columns are matched by node label or, failing that, by node name. Default NULL, which uses the data stored on the network; without either, or when the columns do not match, RMSE is NA. The netobject_ml and netobject_group methods take no data (one passed to them is ignored) and use each network's own.

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. "student" or c("student", "group")); several columns are combined, each observed combination being one actor. Missing or NULL treats all events as one actor.

action

The column holding each event's action (state or code).

time

The timestamp column. Default NULL, in which case the row order (or order) gives the order of the events and no session is split by time. Numeric values are read as Unix timestamps, and POSIXct and POSIXlt values are used as they are, in their own time zone. Text may be ISO 8601 (with Z or an offset), ⁠YYYY-MM-DD HH:MM[:SS]⁠ with -, / or ., day-first or month-first dates, dates with month names, or compact YYYYMMDDHHMMSS, more than 40 layouts in all; text that matches none but reads as a number is taken as a Unix timestamp. A value must match a layout completely, with a four-digit year, so a two-digit year raises an error of class nestimate_bad_input instead of being misread, as does any value no layout reads. Day-first or month-first is decided once for the whole column: any first field above 12 means day-first, any second field above 12 means month-first. When the column cannot decide, values are read day-first with a warning of class nestimate_ambiguous_dates; custom_format settles it. An empty or missing timestamp is not an error: that event is sorted after its session's timed events and starts a session of its own.

order

The column that orders the events: with time, it breaks ties between events with the same timestamp; without time, it gives the order of each session's events. Default NULL (the row order).

session

The column, or columns, identifying explicit sessions (e.g. "course" or c("course", "semester")). Each actor's events in one session form a sequence, further split by time gaps when time is set. Default NULL.

time_threshold

The longest gap, in seconds, between consecutive events of one session; a longer gap starts a new session, numbered s1, s2, ... within its actor and session. Used only with time. FALSE turns the split off, so each actor (or actor-session) forms one sequence however long the gaps. Default 900 (15 minutes).

custom_format

A strptime() format tried before the built-in layouts; values it does not match fall through to them. Default NULL.

is_unix_time

Whether time holds Unix timestamps. TRUE reads a text column as numbers and never as a date layout (a 12- or 14-digit value would otherwise match the compact YYYYMMDDHHMM[SS] layouts); a value that is not a number then raises an error of class nestimate_bad_input. With FALSE (default), text is matched to the date layouts first and read as a Unix timestamp only when it matches none. A numeric time column is always read as Unix timestamps.

unix_time_unit

The unit of numeric timestamps. Default "seconds"; also "milliseconds" or "microseconds". Dates after the year 2500, the usual sign of the wrong unit, raise the warning nestimate_time_unit.

timezone

The Olson time zone (see OlsonNames()) in which timestamps without zone information are read and Unix timestamps are expressed. Timestamps that end in Z, UTC, GMT or a numeric offset such as +02:00 are converted from that offset, so parsing does not depend on the machine's time zone. Default "UTC".

x

For the print() method: a nestimate_data object.

...

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

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 (columns time_T1, time_T2, ...), in timezone (or the zone of a date-time time column), or NULL without time.

statistics

A list with total_sessions, total_actions and max_sequence_length, plus unique_actors (distinct combinations of the actor columns) only when actor was given (without it, every event belongs to one actor).

See Also

build_network

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 V1, V2, ..., or long, with one row per action.

type

How to read data. "sequences" (default) reads wide position columns; "long" converts a long table with long_to_wide(), which needs id_col and action_col; "auto" reads long data when action_col is a column and no ⁠V<number>⁠ column exists, wide data in the opposite case, and, when both exist, long data only if id_col is a column and there are more than twice as many rows as ids. Data with neither raises an error. Whatever the type, the result needs ⁠V<number>⁠ columns; others, such as T1, T2, are not renamed and raise an error.

state_names

The expected states, used with validate. Default NULL, which accepts the states found in the data.

id_col

The column identifying sequences in long data. Default "Actor".

time_col

The column ordering the actions in long data. Default "Time".

action_col

The column holding the actions in long data. Default "Action".

validate

Whether to check the states against state_names; states not listed are named in a warning. Ignored when state_names is NULL. Default TRUE.

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:

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 simplicial_complex from build_simplicial().

x

For the print() and plot() methods: a q_analysis object.

...

For the print() and plot() methods: ignored.

combined

For the plot() method: TRUE (default) draws the Q-vector and the structure vector side by side, which needs gridExtra; FALSE returns them as a named list of ggplots (q_vector, structure_vector).

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_0 for 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 method in build_network(): a single non-empty string. A name already registered is replaced. A method alias, such as "tna", is stored with the warning nestimate_alias_shadowed: build_network() resolves an alias to its built-in method and never calls the registered function.

fn

The estimator function. Its first argument is data, and it must accept ..., because build_network() passes every setting by name. It returns a list with matrix (the square numeric weight matrix), nodes (the node names, in the matrix's order) and directed (TRUE or FALSE); see Details for the optional elements.

description

A short description of the estimator, a single string, shown by list_estimators().

directed

Whether the estimator produces directed networks, TRUE or FALSE. build_network() reads it to decide whether level (the multilevel decomposition) is allowed: a directed estimator refuses it. The edges of the network follow the directed element fn returns, but bootstrap_network() reads this registered flag to build its edge tables, so the two should agree.

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 netobject_group, or an object inheriting from it. Any other object raises an error. A net_mlvar is accepted too, but its print() and summary() find the three layers by their names (temporal, contemporaneous, between): after renaming, print() shows none of the model's dimensions and summary() fails.

new_names

The new names, a character vector in the order of the networks in x: one per network, none missing or empty, and no two the same. Anything else raises an error.

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:

  • a netobject_group, from build_network() with group or from a clustering, whose groups are compared;

  • a netobject, tna model or cograph_network built from sequences;

  • a wide data frame with numbered position columns, as in build_network(), or a character matrix, one row per sequence;

  • a group_tna, read as the group of networks it converts to (see as_netobject()).

Every input except a netobject_group needs group. One-hot data, association networks and data frames with extra columns raise nestimate_bad_input. With actor, a tna model must keep its metadata, as one built with tna::prepare_data() does. For print() and plot(): a sequence_compare() result.

group

The group of each sequence: the name of a column of a data frame or matrix x (that column is then not read as a position), or a vector with one label per sequence. Ignored for a netobject_group; required otherwise. At least two groups are needed. Sequences with a missing group are left out of the counts with a warning of class nestimate_missing_group. Default NULL.

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 3:5.

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

test

The inference: "permutation" (default), "chisq" or "none"; see Details.

iter

The number of permutations for test = "permutation", a positive whole number; ignored otherwise. With iter = 1 the effect size is undefined, and a warning says so. Default 1000.

adjust

The p-value adjustment, any method of stats::p.adjust() ("holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr" or "none"). Default "fdr" (Benjamini-Hochberg).

actor

The column identifying the actor each sequence belongs to, or several columns for nested levels, outermost first (c("Group", "Student")); see Nested data and actor. With several levels, labels are shuffled at the level where they are assigned, within the units above it, and n_actors counts the innermost level. For a netobject_group, netobject or tna model the columns are looked up in the network's ⁠$metadata⁠ (for example the Group column kept by build_network() when students are nested in teams); for a data frame or matrix x, they are columns of x, which are then not read as positions. Only used with test = "permutation"; with "chisq" or "none" it is ignored with a warning of class nestimate_ignored_argument. Duplicated, missing or empty names, and levels that are not nested outermost first (a level that adds no units below the one before it), raise an error of class nestimate_bad_actor; a column that is absent or has missing values, nestimate_actor_missing; a column that does not give one id per sequence, nestimate_actor_misaligned. Default NULL: every sequence is shuffled on its own.

n

For print(): the number of patterns shown, the first ones of the pattern table. Default 10.

digits

For print(): the decimals of the counts' shares, residuals and effect sizes. Default 2; p-values show 3 significant digits.

...

Not used.

object

For the summary() method: a net_sequence_comparison.

format

For summary(): "wide" (default), the pattern table, one row per pattern with a freq_, prop_ and resid_ column per group; "long", one row per pattern and group, with columns pattern, length, group, count, proportion, residual and the pattern's effect_size (or statistic) and p_value.

top_n

For plot(): the number of patterns drawn, the first ones after ranking by sort. Default 10.

style

For plot(): "auto" (default) draws the back-to-back pyramid for exactly 2 groups and the heatmap for any other number; "pyramid" and "heatmap" force one. "pyramid" with other than 2 groups raises an error.

sort

For plot(): how to pick and order the patterns. "statistic" (default) ranks them by the absolute effect size after a permutation test, by the chi-square statistic after a chi-square test, and by the largest absolute residual without a test. "frequency" ranks them by their total count across the groups.

alpha

For the pyramid: the significance level for the p-value labels. Patterns with p_value < alpha are starred and drawn in bold dark text, the rest in plain grey. Default 0.05. The heatmap and a comparison without a test ignore it.

show_residuals

For the pyramid: whether to print each bar's standardised residual inside it. Default FALSE. The heatmap always prints the residuals.

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 iter times 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 not min_freq keeps 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), where b counts the permutations with a statistic at least as large as the observed one, so it cannot fall below 1 / (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; with iter = 1 the effect size is NA, since at least two permutations are needed). The shuffles use R's random number generator: call base::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 group ⁠freq_<group>⁠ (the count), ⁠prop_<group>⁠ (the count as a share of all k-grams of that length in the group, rare ones included) and ⁠resid_<group>⁠ (the standardised residual). With test = "permutation" also effect_size and p_value; with test = "chisq", statistic and p_value. The p-values are adjusted. Rows are ordered by ascending p_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_freq in every group.

params

The settings used: sub (after dropping lengths longer than the sequences), min_freq, test, iter and adjust; with actor and test = "permutation" also actor (the column name), n_actors (the number of distinct actors among the sequences with a group) and design ("between" when every actor lies in one group, "within" when every actor lies in several, "mixed" otherwise). With several actor levels, n_actors counts the innermost level, design reads "<level>: <design> (<n> actors)" for every level, and actor_levels is a data frame with one row per level: level, n_actors, n_pure and n_crossed (the units the shuffle met at that level, inside crossed units above, in one group or in several) and design ("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 extract_sequences() accepts.

favorable

The favourable states; giving them adds integrative_potential. States that do not occur in the data are ignored, and an error of class nestimate_bad_input is raised when none of them occur. Default NULL.

omega

The exponent of the position weights in integrative_potential; a positive value gives later positions more weight, 0 weights every position equally and a negative value gives earlier positions more weight; any single finite number is accepted. Ignored without favorable. Default 1.

meta

Whether to put each sequence's covariates (actor, session, group, metadata) before the indices. Default FALSE.

cols

The state columns of a wide data frame, as in extract_sequences(). Default NULL.

actor, action, time

The actor, action and timestamp columns of a long event log; setting action marks x as one. Default NULL. With group and sequences that are not an event log (a network, a wide table), actor instead names the covariate that nests the sequences (the session of a half-session, the student of a course), and the permutation test shuffles the group labels within it (see Comparing groups). For a network built with actor, the default nests the sequences in that actor (its .session_label), so the two halves of one session are compared within the session.

group

A covariate of the sequences holding each sequence's group: for a grouped network its group column (for example "phase" after mark_phases()), for a wide table one of its non-state columns. With group, the result compares the indices between the groups instead of listing them per sequence. A grouped network is compared by its own groups by default; meta = TRUE lists its sequences instead. A name that is not a covariate of the sequences, or fewer than two groups, raises an error of class nestimate_bad_input. Default NULL.

indices

The indices to return, by name (for example c("valid_n", "transition_rate")). Default NULL returns them all. A name that is not an index raises an error of class nestimate_bad_input.

iter

The number of permutations of the group comparison, a whole number of at least 1. Default 1000.

adjust

The method of stats::p.adjust() applied to the p-values of the group comparison. Default "BH".

format

The layout of a group comparison: "long" (default), one row per index and group, or "wide", one row per index with a column per group. Ignored without group.

...

Further arguments passed to prepare() for a long event log, such as time_threshold or order.

n

For print() of a group comparison: the number of indices shown. Default 10.

digits

For print(): the decimals of the means, SDs and effect sizes. Default 2; p-values show 3 significant digits.

object

For summary(): a group comparison from sequence_metrics(group = ).

i, j

For [: rows and columns, as for a data frame. A subset of a group comparison is a plain data frame.

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

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, where a is the number of states in the data; NA when 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; NA when 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 weights position^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) that TraMineR::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 len states, e.g. A->B->C.

"gapped"

Two states separated by gap positions of any state, e.g. ⁠A->*->B⁠ (gap 1) or ⁠A->**->B⁠ (gap 2).

"repeated"

Runs of len identical 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 extract_sequences() accepts: prepared data, a long event log (with action), a wide data frame or character matrix, a netobject, netobject_group or tna model.

type

The kind of pattern to find: "ngram" (default), "gapped" or "repeated". Ignored when pattern is given.

len

The pattern lengths, in states, for "ngram" and "repeated": positive whole numbers. Default 2:5.

gap

The gap sizes, in positions, for "gapped": positive whole numbers. Default 1:3.

min_freq

The fewest times a pattern must occur to be kept, at least 1. Default 2.

min_support

The smallest share of sequences that must contain a pattern for it to be kept, between 0 and 1. Default 0.01.

start, end

States a pattern must begin (start) or end (end) with, one of them at least; wildcards do not count. Default NULL (any).

contain

States a pattern must include, one of them at least. Default NULL (any).

pattern

A template to search for instead of discovering all patterns. Each * stands for one position holding any state (⁠**⁠ for two), so "A->*->B" finds every three-state pattern from A to B, each concrete instance as its own row. States are joined by "->" (spaces around it are allowed), and a template may mix fixed states and wildcards or hold no wildcard at all. type, len and gap are then ignored. A template with an empty step, such as "A->->B", raises nestimate_bad_input. Default NULL.

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 netobject_group is grouped by its own groups when group is NULL. "last_obs" takes each sequence's last observed state as its group and removes every state that ends some sequence from all sequences, for data whose final state codes the outcome (such as an appended "pass" or "fail"), as codyna's last_obs does. Sequences with a missing group are dropped with a warning of class nestimate_missing_group. A column not found, a vector of the wrong length or a single group raise an error of class nestimate_bad_input. Default NULL (no test).

reference

For two groups: the reference group, so the odds ratio is that of the other group. Default NULL, the first group in sorted order; a value that is not a group raises an error of class nestimate_bad_input.

adjust

The multiplicity correction of the group test's p-values, one of p.adjust.methods (see stats::p.adjust()). Default "BH".

top

The number of rows to return, a positive whole number: the first in the output order. Default NULL (all).

cols

The state columns of a wide data frame, as in extract_sequences(). Default NULL.

actor, action, time

The actor, action and timestamp columns of a long event log; setting action marks x as one. Default NULL.

format

With group: "long" (default), one row per pattern and group, or "wide", one row per pattern with a column per group. Ignored without group.

...

Further arguments passed to prepare() for a long event log, such as time_threshold or order.

n

For print() of a group comparison: the number of patterns shown. Default 10.

digits

For print(): the decimals shown. Default 2; p-values show 3 significant digits.

object

For summary(): a group comparison from sequence_patterns(group = ).

i, j

For [: rows and columns, as for a data frame. A subset of a group comparison is a plain data frame.

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

occurrences as a share of all patterns of the same length.

n_sequences

The number of sequences that contain it.

support

n_sequences divided 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:

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:

event log

A data frame with one row per action and action naming the action column (with actor, time and order as needed). It is converted with prepare(): one row per actor, or per actor-period with periods.

data frame or matrix

One row per sequence, one column per time point; for a data frame, cols names the position columns when they are not a numbered run.

netobject

A network built from sequences; its sequence data is drawn. A network without its sequence data (built from a matrix) raises an error, and a one-hot or association network raises an error of class nestimate_bad_input.

net_clustering

From build_clusters(): its sequences, with the cluster assignments as groups and its distance matrix as the heatmap's dendrogram.

netobject_group

From cluster_network() or build_network() on a clustering: the full sequences and assignments carried by the clustering, or, for a plain group split, the groups' sequences stacked and labelled by group.

net_mmm

From build_mmm(): its sequences (or, when the fit stores none, those of its first component model), with the hard assignments as groups.

tna

A tna model; its integer-coded sequences are decoded to their state labels. A group_tna is drawn as the group of networks it converts to (see as_netobject()), one panel per group.

mcml

From build_mcml(), built from sequences (an mcml built from a matrix carries none and raises an error). It gives the multichannel figure: one panel per cluster plus a macro Summary panel. type = "heatmap" and "index" draw the carpet (each channel's own states solid, the other clusters a faded wash); type = "distribution" draws the stacked distribution (add normalize = TRUE for a TraMineR-style seqdplot, where each time point sums to 1).

For the print() method: an mcml_sequence_plot.

type

The view: "heatmap" (default), "index" or "distribution".

sort

How rows are ordered, in the heatmap and within each panel of the index view. "lcs" (default) orders them by a Ward (ward.D2) hierarchical clustering of their longest-common-subsequence distances, and any other build_clusters() distance ("hamming", "osa", "lv", "dl", "qgram", "cosine", "jaccard", "jw") does the same with that distance. "frequency" clusters the rows by how often each state occurs in them. "start" sorts the rows alphabetically by their states from the first time point on, "end" from the last time point back; these two draw no dendrogram. A clustering input (a net_clustering, or a netobject_group from cluster_network()) orders the heatmap by a hierarchical clustering of its own distance matrix, using its linkage when it was clustered hierarchically and ward.D2 otherwise (for example with the default pam), unless tree is given.

tree

A hclust, dendrogram or agnes object that gives the row order of the heatmap and is drawn beside it; it overrides sort. It must have one leaf per row. Default NULL.

group

The groups to draw in separate panels, one value per sequence (nrow(x) values), for the index and distribution views; the heatmap ignores it. NULL (default) uses the cluster assignments of a net_clustering, net_mmm or netobject_group input, and draws one panel otherwise. Index panels are titled "Cluster <label>", whatever the grouping. With periods, group instead names a column of the event log (or of the network's metadata) that is constant within actor, such as a class or a condition: one panel per value, one row per actor, all panels on the same period axis. With an event log it works only together with periods; otherwise it raises an error of class nestimate_bad_input.

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. x must be an event log with actor and action, or a netobject built with actor and session = periods, so that each actor-period pair holds one sequence; anything else raises an error of class nestimate_bad_input. The plot then has one row per actor and the time axis is split into equal-width blocks, one per period. A Date column gives one block per calendar day and a whole-number column (a day or week counter) one block per number, from the first to the last, so a period in which nobody acted is an empty block; factor levels give their order (an unused level is an empty block); other columns are sorted. Ticks mark the period boundaries and each label sits under its block; tick thins the labels, and the x-axis label defaults to the column name. Heatmap and index views only (the distribution view raises an error of class nestimate_bad_input). trim then counts periods, not time points. Default NULL plots the sequences as they are.

period_unit

With a date periods column (a Date, a POSIXct or text in the form "2026-03-05"), the length of one block: "day" (default), "week" (weeks starting on Monday, labelled by their Monday) or "month" (labelled by their first day). Every week or month from the first to the last is a block, so one in which nobody acted is an empty block. "week" or "month" with a periods column that is not a date raises an error of class nestimate_bad_input.

fill

With periods, how an actor's steps fill a block. "stretch" (default) spreads them over the whole block, so one step fills it and three steps take a third each; the cell width differs between actors. "pad" gives every block as many fixed slots as the busiest actor-period and leaves unused slots as NA, so a slot is the same step position for every actor (minor ticks mark the slots when there are at most 60 in all). With periods, empty space is white unless na_color is given, so it is never confused with a state drawn in grey. Repeats of a state merge into one spell; cell_border = "white" (TraMineR's border) outlines each action so they show as separate, equal shares of the period. Setting fill without periods raises an error of class nestimate_bad_input; an mcml ignores it with a warning.

actor, action, time, order

For an event log: column names, as in build_network(). Giving action declares x an event log (one row per action); actor identifies who acted (one row per actor in the plot), and time and order put each actor's actions in order (otherwise row order is used). Without periods, a time column also splits an actor's actions into sessions at gaps over 15 minutes, as prepare() does; with periods it does not, so each actor-period is one sequence. actor, time or order without action, a column that is not in x, and a missing actor or period raise an error of class nestimate_bad_input. Default NULL each.

scale, geom, na

For the distribution view, passed to distribution_plot(): scale is "proportion" (default) or "count", geom is "area" (default) or "bar", and na = TRUE (default) draws missing cells as a band of their own. For an mcml distribution, na = FALSE drops the NA (ended) band and shows every time point as shares of the sequences still running there, so each panel stacks to 100 percent (cluster panels only with rest = "clusters" or "pooled"; a time point where no sequence is running stays empty).

normalize

For an mcml distribution only: TRUE normalises each time point to sum to 1 within its channel (the composition of TraMineR's seqdplot); FALSE (default) shows prevalence, capped with an NA band.

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 mcml multichannel figure included. Default NULL plots everything.

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 trim = 0.9 removes the quiet time points holding the last tenth of the states, which is what a long tail consists of, and those with no data. A value ⁠>= 1⁠ is an absolute cut (trim = 50 keeps the first 50 time points). With periods the unit is the period block: trim = 60 keeps the first 60 periods and a fraction judges each period by its actions.

The second number ends each row earlier and never removes a row, counted over the time points kept by the first: a value ⁠>= 1⁠ keeps each row's first that many observed states (trim = c(60, 5)), a fraction its first share of them (trim = c(0.9, 0.9)). What is left stays in place; the row is white after that point. NA leaves an axis alone (trim = c(NA, 5)). Either way only the drawing changes, not the data.

panel

For an mcml distribution only: which panels to draw. "both" (default) stacks the macro Summary channel and the per-cluster channels on one figure, each with its own legend; "summary" draws the macro channel alone, keyed and coloured by cluster; "channels" draws the per-cluster channels alone, keyed and coloured by state. The macro channel is keyed by cluster and the rest by state, so a cluster and a state can land on the same colour; drawing one panel avoids that and gives it a default title. With an mcml heatmap or index view, a value other than "both" raises an error.

expand

For an mcml: the clusters whose member states are shown individually in the Summary panel; "all" or TRUE expands every cluster. The per-cluster panels are unaffected. Default NULL keys the Summary panel by cluster.

combine

For an mcml: clusters to merge into one channel. A character vector merges one group (e.g. combine = c("Cognitive", "Affective")); a list merges several, and its names label the merged channels (default label "Cognitive + Affective"). A merged group acts as one cluster throughout the figure: one per-cluster panel holding all its states, one key in the Summary panel, and one faded band in the other panels. expand is resolved after merging, so it can name the merged label. An unknown cluster, a group of fewer than two, or a cluster in two groups raises an error. Default NULL draws the partition as built.

rest

For an mcml: how a cluster's panel shows the time its subjects spend in other clusters. "clusters" (default) draws one faded band (or wash, in the carpet) per other cluster; "pooled" draws all other clusters as one grey band labelled rest_label; "none" leaves them blank, so the panel shows only its own states. In the distribution view "none" drops the NA (ended) band too, and the panel's height at each time point is the share of subjects in that cluster. Ignored with normalize = TRUE, which rescales each panel to its own states. The Summary panel is unaffected.

rest_label

For an mcml: the legend text for time spent in other clusters. Default "Other states"; "Others" or "Rest of states" are alternatives. The pooled band (rest = "pooled") takes it as is; the per-cluster bands read "Social (Other states)". A label equal to a state or cluster name, or to "NA", raises an error. combine, expand, rest and rest_label on any input other than an mcml raise an error.

trim_clusterwise

For a grouped index or distribution view with a fractional trim: FALSE (default) computes one cut on the pooled data and applies it to every panel, so all panels share the same width and the time axes stay aligned; TRUE judges the time points within each group, so panels can end up at different widths. An absolute trim (⁠>= 1⁠) ignores it, since the cut is the same everywhere.

row_gap

The vertical gap between rows of the index view, as a fraction of the row height, in [0, 1). Default 0 (dense, like the heatmap); 0.15 gives visible separators when there are few rows.

dendrogram_width

The width of the heatmap's dendrogram panel, against a carpet width of 4: the default 1.2 makes the dendrogram 0.3 times as wide as the carpet. Used only when a dendrogram is drawn.

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. sort = "start") and in the other views. Default NULL (no separators).

k_color

The colour of the cluster separator lines. Default "white".

k_line_width

The line width of the cluster separators. Default 2.5.

state_colors

Colours for the fill keys, in one of two forms: unnamed, one colour per state in level order (states are ordered as sort(unique(...))); or named, a lookup where only the keys you name are overridden and every other key keeps its default (Okabe-Ito). Names this figure does not draw are dropped with a message naming them, so one project-wide palette can be handed to every plot and each takes the keys that apply to it. Default NULL uses the palette attached to x with set_state_colors(), if any; a palette given here wins for this figure.

For an mcml the named form reaches the whole figure, not only the states: a cluster name colours its Summary band, its channel strip and its faded band in the other panels, and a group merged by combine is named by its label (the list name you gave it, or "A + B"). rest_label is a key too. So state_colors = c(plan = "#0072B2", "Planning + Monitoring" = "#D55E00") recolours one state and one combined cluster and leaves the rest of the palette alone.

na_color

The colour of missing cells. Default "grey90"; with periods, "white" unless given.

cell_border

The colour of each cell's border. Default NA (no border).

frame

Whether to draw a box around each panel; axis ticks and labels appear either way. Default FALSE.

width, height

Device dimensions in inches. In an interactive session, giving either opens a new graphics device with grDevices::dev.new() (the other defaults to 7); otherwise they are ignored. In knitr chunks, use the fig.width and fig.height chunk options instead. Default NULL.

main

The plot title. Default NULL: no title, apart from "n = N" when show_n = TRUE. With several groups, main is drawn once above the panels, and not at all when combined = FALSE.

show_n

Whether to append "(n = N)" to the title (to each panel title when grouped). Default TRUE.

time_label, xlab

The x-axis label; xlab is an alias that wins when given. Default "Time" (with periods, the period column's name).

y_label, ylab

The y-axis label of the distribution view; ylab is an alias. Default NULL, which distribution_plot() reads as "Proportion" or "Count" according to scale.

tick

Label every tick-th time point on the x-axis. Default NULL thins the labels to about 15.

ncol, nrow

The panel grid of the grouped index and distribution views. Default NULL: with neither given, ncol = ceiling(sqrt(G)) for G groups and nrow = ceiling(G / ncol); with one given, the other follows. With combined = FALSE the grid does not affect the layout, but ncol * nrow must still be at least the number of groups or an error is raised.

combined

For the grouped index and distribution views: TRUE (default) arranges the groups on one figure with graphics::layout(); FALSE draws each group on its own page, at full size with its own legend. A single group ignores it, and the heatmap is always one figure.

legend

The legend position: "right", "bottom" or "none". Default NULL, read as "right" for every view.

legend_size

The legend text size. Default NULL scales it with the device width so the legend stays in proportion on a 5-inch and a 12-inch figure (between 0.65 and 1.2).

legend_title

The legend title. Default NULL (none).

legend_ncol

The number of legend columns. Default NULL: one row for a bottom legend, one column for a right legend.

legend_border

The colour of the legend swatches' borders. Default NA (none).

legend_bty

The legend box: "n" (default, none) or "o" (boxed).

cols

For a wide data frame: the columns holding the positions. Needed when they are not a numbered run (T1, T2, ...), when one of them is called action, or when any other column sits beside them; given for any other input it raises an error of class nestimate_bad_input, except for an mcml, which ignores it with a warning. Default NULL.

...

For the print() method: ignored.

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 to palette) and sort_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) and groups (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 the fill = "pad" layout, named "<period>.<slot>"), palette, levels, periods (the period labels in plotted order, after trim) and fill; with group, also groups (the panel labels) and orders (one row order per panel, indexing the actors), ord being their concatenation.

distribution

What distribution_plot() returns: counts, proportions, levels, palette and groups.

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:

Summary

The 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:

  1. combine merges 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.

  2. expand opens clusters (including a merged group, by its label) into their member states in the Summary panel only.

  3. rest and rest_label set how a cluster's panel shows the other clusters: one faded band per cluster labelled "<cluster> (<rest_label>)" (rest = "clusters"), one grey band labelled rest_label ("pooled"), or nothing ("none").

  4. na (distribution only) keeps the NA band 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 unless rest = "none"). normalize = TRUE instead rescales each cluster panel to its own states, which ignores rest and na.

panel draws the Summary or the cluster panels alone, and trim cuts the time axis for every panel at once.

Methods

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 netobject built by build_network() from long data, or a net_mmm (build_mmm()) or net_clustering (build_clusters()) fitted on such a network. Any other object raises an error of class nestimate_no_session_ids (see Errors).

...

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 actor and session columns given to build_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_mmm or net_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:

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 netobject, netobject_group, mcml or htna; any other object raises an error.

colors

The palette: a named character vector of colours, such as c(plan = "#0072B2", monitor = "#D55E00"). Names are states (for a network built with labels, the labels it draws), and for an mcml may also be cluster names. A name the object does not carry is reported in a message and draws nothing, so one project-wide palette can be attached to every object. States left unnamed are dealt the Okabe-Ito colours the palette does not already use, in the object's state order (recycled when there are more such states than colours). The palette replaces any palette set earlier, and NULL removes it. An unnamed vector raises an error.

value

The palette, as for colors, in the replacement form state_colors(x) <- value.

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 simplicial_complex from build_simplicial().

normalized

Whether to divide each count of dimension k by the largest possible one, choose(n_nodes - 1, k), the number of k-simplices a node can be in. Default FALSE.

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 netobject, cograph_network, tna model or square weight matrix (one row); a netobject_group, or a list of single networks or matrices (one row per member, named by the list, or network_1, network_2, ... when unnamed); or an mcml object (one row per cluster, from its within-cluster networks; one built without them raises an error).

threshold

The smallest absolute edge weight that makes an edge, passed to build_simplicial(). Default 0 (every non-zero edge). A vector sweeps it, giving one row per network per threshold. Values must be finite and not negative. type = "vr" and type = "pathway" ignore it, although the threshold column still records it.

max_dim

The highest simplex dimension built, a whole number of at least 1 (a fractional value is truncated). Default 4. When a network holds a larger clique, the complex is truncated and raises the warning nestimate_truncated_complex, which concerns the Betti number of dimension max_dim, so it affects b1 only when max_dim = 1.

normalize

Whether to divide the simplex counts (d1 onwards and higher_order) by the number of nodes, so networks of different size are comparable; n_edges stays a count. Default FALSE.

type

The complex construction passed to build_simplicial(): "clique" (default), "pathway", "vr" or its alias "rips". "pathway" needs networks of class netobject or tna, from which a higher-order network is built; a matrix, a bare cograph_network or an mcml (whose cluster layers are matrices) raises an error.

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 build_network() with method "relative" or "frequency" (or a bare cograph_network of one), a grouped one (netobject_group, for example build_network() of a build_clusters() result), a tna model or a group_tna (one landscape per group), or a wide sequence data frame or matrix. A network must count one-step transitions (a window wider than one position raises an error) and carry its sequences; a network of another method (for example "glasso") raises an error of class nestimate_not_markov. For the print() and plot() methods: a net_landscape object.

states

Every state, each named once, in the order to draw them (for example from least to most engaged). Default NULL, the alphabetical order. A vector that leaves out, adds or repeats a state raises an error of class nestimate_bad_input.

iter

The number of bootstrap resamples of sequences behind the intervals, a non-negative whole number. Default 1000; 0 skips the resampling and leaves the intervals NA.

ci_level

The interval level, a number between 0 and 1. Default 0.95.

seed

A seed for the resampling. It applies to this call only: the session's random state is restored afterwards. Default NULL.

cols

For a wide data frame: the columns holding the positions. Needed when they are not a numbered run (T1, T2, ...) or one of them is called action; such a frame without cols raises an error of class nestimate_bad_input. Default NULL.

object

For the summary() method: a net_landscape object.

table

For the summary() method: which table to return, "cups" (default), "exits" or "circulation". The circulation exists for three states only; asking for it otherwise raises an error of class nestimate_bad_input.

...

Ignored.

digits

For the print() method: decimal places (the circulation gets two more). Default 2.

state_colors

For the plot() method: colours for the states, for this figure only. Named, c(state = "#0072B2"), it overrides the states it names; unnamed, it gives one colour per state in states order. Default NULL: the colours of the network the result came from (set with set_state_colors()), Okabe-Ito for the rest, as every figure of that network draws them.

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 netobject, netobject_group, mcml or htna. A tna model or a group_tna (package tna) is first rebuilt as a network from its own sequences (see as_netobject()). Any other object raises an error.

...

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

set_state_colors.

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 netobject, netobject_group, mcml or htna network built from sequences, or the state_freq result of plot_state_frequencies(), whose table is returned as drawn. A tna model or a group_tna (package tna) is first rebuilt as a network from its own sequences (see as_netobject()). A network without sequence data raises an error; in a netobject_group or mcml, groups without it are left out, and an error is raised only when none has any. Other classes raise an error.

...

Not used. The mcml method raises an error for any argument it does not take; the other methods ignore it.

include_macro

For an mcml: whether to add a "macro" group in front, holding the state counts over all clusters. Default FALSE.

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 tna model or a netobject built from sequences. A data frame needs position columns named as a numbered run (T1, T2, ...); any other frame, a one-hot or association network and a 0/1 matrix raise an error of class nestimate_bad_input.

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: netobjects, cograph_networks or square numeric matrices. A tna model (package tna) is first rebuilt as a network from its own sequences (see as_netobject()). They must have the same number of nodes, with the same labels in the same order, or an error is raised; any other kind of object raises an error too. A matrix without dimnames is labelled V1, V2, ..., so it matches only a network with those labels. The difference is directed when either network is directed (a network by its own directed flag, a matrix, or a cograph_network without that flag, when its weights are not symmetric) or when the difference itself is not symmetric. For the print() method: x is the netdifference object.

max_print

For the print() method: the most edges to list; the number left out is reported. Default 12.

...

For the print() method: ignored.

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 netobject or cograph_network with non-negative transition weights, a tna model, a numeric transition matrix, or wide sequence data (a data frame or a character matrix, one row per sequence) that holds a numbered run of positions (T1, T2, ...), from which a relative transition network is built; other columns are set aside with a message. For a frame without such a run, build the network with build_network() (⁠state_cols =⁠ or ⁠action =⁠) and pass that. A netobject_group gives one result per group. An association network (cor, pcor, glasso, ising, mgm) or a matrix with negative entries raises an error of class nestimate_not_markov. A group_tna (package tna) gives one result per group, as a netobject_group does. For the print() and plot() methods: a transition_entropy() result; print() also takes a group result.

base

The logarithm base, which sets the unit: 2 (default) for bits, exp(1) for nats, 10 for hartleys. Any finite number greater than 1; another value raises an error of class nestimate_bad_input.

normalize

Whether rows that do not sum to 1 (a frequency network, a count matrix) are divided by their sums, with a warning. With FALSE, such rows raise an error. Default TRUE. A state with no outgoing transitions (a row summing to zero) is an error either way.

digits

For the print() methods: decimal places of the values. Default 3. The normalised values always print with three decimals.

...

For the print(), summary() and plot() methods: not used.

object

For summary(): a transition_entropy() result.

table

For summary(): "states" (default), the per-state table, or "chain", the chain-level quantities.

title

For plot(): the plot title. Default "Transition Entropy".

fill

For plot(): the bar fill colour. Default "#0072B2", the Okabe-Ito blue.

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_entropy divided by the ceiling \log_b n, in [0, 1]; all zeros when n = 1.

stationary

Named numeric vector: the stationary distribution \pi.

stationary_entropy

H(\pi) = -\sum_i \pi_i \log_b \pi_i, the entropy of \pi read as an independent draw each step; an upper bound on the entropy rate.

stationary_entropy_norm

stationary_entropy divided 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_rate divided 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 of P equal to \pi).

redundancy_norm

The relative redundancy (H(\pi) - h(P)) / H(\pi), the share of the stationary entropy that order-1 memory removes; not redundancy divided by \log_b n. 0 when H(\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 cograph_network.

Value

TRUE, invisibly, when x passes every check. Otherwise an error that lists every check it failed.

See Also

as_netobject

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 build_simplicial() reads (a netobject, tna model, cograph_network or net_hon).

threshold

The smallest absolute edge weight an edge needs to enter, as in build_simplicial(). Default 0.

x

For the print() method: a net_simplicial_check from verify_simplicial().

...

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 netobject (from build_network() or any builder), a cograph_network, or a square numeric weight matrix, with at least 3 nodes. A tna model (package tna) is first rebuilt as a network from its own sequences (see as_netobject()). A latency network raises an error of class nestimate_latency_resampling. Other input raises an error. For print() and plot(): a vertex_bootstrap() result.

iter

The number of bootstrap replicates, at least 2. Default 1000.

ci_level

The significance level of the confidence intervals, not their coverage: 0.05 (default) gives 95% intervals. Must lie strictly between 0 and 1.

ci_method

How the intervals are formed. "percentile" (default) takes the ci_level / 2 and 1 - ci_level / 2 quantiles of the replicates; "basic" reflects them around the observed value, 2 * observed - upper and 2 * observed - lower (Davison & Hinkley 1997, eq. 5.6).

statistics

The built-in statistics to compute (see Details). Default NULL: all of them, with reciprocity only for a directed network. A name that is not available for the network, such as reciprocity on an undirected one, raises an error.

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 nestimate_bad_input. Default NULL.

directed

Whether the network is directed, which decides how collisions are filled and whether reciprocity is available. Default NULL reads the network's own directedness, and for a matrix (or a network that records none) treats an asymmetric matrix as directed.

seed

A seed passed to set.seed() before resampling, so the run can be repeated; the session's random-number stream then continues from it. Default NULL uses the current stream.

digits

For the print() method: the number of decimals shown. Default 3.

...

Not used.

object

For the summary() method: a net_vertex_bootstrap result.

bins

For the plot() method: the number of histogram bins. Default 30.

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:

density

The share of non-zero off-diagonal cells.

mean_weight

The mean of the non-zero off-diagonal weights.

centralization

Freeman-type strength centralisation, sum(max(s) - s) / ((n - 1) * max(s)), where s is 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.

reciprocity

Directed 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, iter rows 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: netobjects, cograph_networks, square weight matrices, or net_vertex_bootstrap results computed beforehand. A precomputed result is used as it is, so iter, statistics, statistic_fn and directed do not apply to it. The two must cover the same statistics: a mismatch, such as a directed network's reciprocity against an undirected network, or two precomputed results with different statistics, raises an error rather than comparing a subset. A tna model (package tna) is first rebuilt as a network from its own sequences (see as_netobject()). A latency network raises an error of class nestimate_latency_resampling. For the print() and plot() methods, x is a net_vertex_comparison result.

iter

The number of bootstrap replicates, at least 2. Default 1000.

ci_level

The significance level of the normal-approximation intervals for the differences: 0.05 (default) gives 95% intervals. It is also passed to the bootstraps run here; with a precomputed result, the differences still use this level.

statistics

The built-in statistics to compare, as named for vertex_bootstrap(): density, mean_weight, centralization and, for directed networks, reciprocity. Default NULL: all that apply. A name not available for a network raises an error.

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 nestimate_bad_input. Default NULL.

directed

Whether the networks are directed, which decides how collisions are filled and whether reciprocity is available; one value applies to both networks, not to a precomputed result. Default NULL reads each network's own directedness, and for a matrix (or a network that records none) treats an asymmetric matrix as directed.

seed

A seed passed to set.seed() once, before both bootstraps run, so the comparison can be repeated; the session's random-number stream then continues from it. Default NULL uses the current stream.

labels

Two names for the networks, used in the print header and the plot axis. The columns are always observed_x (the first network) and observed_y (the second). Default c("x", "y").

digits

For the print() method: the number of decimals shown. Default 3.

...

Not used.

object

For the summary() method: a net_vertex_comparison result.

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

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 NULL, which adds a column id holding the row number of the wide input (replacing any existing column of that name). A name that is not a column raises an error.

time_prefix

The prefix of the time point columns: with "V" (default), the columns V1, V2, ... are read. No column matching it raises an error.

action_col

The name of the state column in the output. Default "Action".

time_col

The name of the time column in the output. Default "Time".

drop_na

Whether to drop the rows whose state is missing, such as the padding after a shorter sequence ends. Default TRUE.

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; with id_col = NULL it is called id and 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 actor column. A column named in codes may hold only 0, 1 or missing; a missing cell counts as inactive, and any other value raises an error of class nestimate_bad_input. Under the default codes = NULL such a column is not read as a code.

method

The network to build: "transition" (default), directed, from the codes of one window to those of the next; "cooccurrence", undirected, between the codes of the same window; or "both", which returns the two networks together as a wtna_mixed.

type

The weights: "frequency" (default) keeps the counts, and "relative" divides each row by its sum (a row without counts stays zero). On a co-occurrence network "relative" gives an asymmetric matrix, the co-occurrence conditional on the row's code, so the network is then directed (each cell its own edge); keep "frequency" when symmetric counts are needed.

codes

The one-hot columns, as names, as column positions, or as a single "first:last" string naming a range of adjacent columns. Default NULL, every numeric or logical column holding only 0, 1 and missing values, except actor. At least two codes are needed, and a name that is not a column stops wtna().

window_size

The number of consecutive rows in a window, a whole number of at least 1. Default 3. With 1 there is no windowing: transitions are counted from each row to the next, and co-occurrence within each row, and mode is ignored.

mode

How windows are formed when window_size is above 1. "non-overlapping" (default) cuts the rows into consecutive, separate blocks of window_size rows. "overlapping" first replaces the rows by one row per sliding window of window_size rows (step 1), marking a code active when it is active in any of them, so n rows give n - window_size + 1 windows, and then counts those in blocks of window_size, as tna::import_onehot(window_type = "sliding") does.

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 NULL, all rows as one sequence. A missing identifier raises an error of class nestimate_bad_input, and a name that is not a column stops wtna(). With several columns, the initial-state distribution groups the rows by the first column only.

x

For the print() method: a wtna_mixed object.

...

For the print() method: ignored.

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;

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

build_network

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")