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
actionset).- 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,TRUEadds 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, asstart.- 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
sessionortime_threshold; in one-hot data, each actor's rows. DefaultNULL.- action
The column holding each event's state; setting it declares the data an event log. Column names give no role:
action,actor,timeandsessionare read only when set. A column calledActionwith nothing declared raises an error of classnestimate_bad_input, and an undeclared time or session column besideactionis named in a message of classnestimate_column_role. DefaultNULL.- time
The timestamp column of an event log. Events are ordered by it, and a gap longer than
time_thresholdstarts a new sequence. DefaultNULL.- session
The column identifying sessions in an event log; each session is its own sequence, also without
actor. DefaultNULL.- 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.
FALSEturns the split off, so each actor (or actor-session) is one sequence. Default900.- timezone
The Olson time zone for timestamps without an offset (passed to
prepare()); timestamps with an offset, such as...Zor+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, ..., or1,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 classnestimate_bad_input: nothing says whether they are positions or one-hot codes. DefaultNULL.- 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 classnestimate_column_role, and listing it here or instate_colssettles it. DefaultNULL.- 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. DefaultNULL.- 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 inc("rank", "minmax"). DefaultNULL(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 vectorc(name = "label")or a named list. It rewrites the node labels and the weight matrix's dimnames; nodes not listed keep their names. DefaultNULL.- params
Settings for the estimator, as a named list, as for
build_tna(); alsoduration(one value per position, accumulated into times) ortime_matrix(one row per sequence, one column per position), which measure the distance in time instead of positions. Defaultlist().- ...
Further arguments for
build_network():format("auto","wide","long"or"onehot", to force a reading ofdata), and for event logsprepare()'s time optionsunix_time_unit,is_unix_timeandcustom_format.methodcannot be given: each alias has its own (error of classnestimate_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)
#> Network (method: ngram) [directed]
#> Weights: [38.000, 861.000] | mean: 357.667
#>
#> Strongest edges (9 of 9):
#> from to weight
#> Active Active 861
#> Average Average 853
#> Active Average 324
#> Disengaged Disengaged 292
#> Average Active 285
#> Average Disengaged 266
#> Disengaged Average 233
#> Disengaged Active 67
#> Active Disengaged 38
#>
#> extract_edges(include_self = TRUE) lists every edge; extract_transition_matrix() gives the weight matrix;
#> extract_initial_probs() the initial probabilities.
build_ngram(trajectories, n_gram = 3)
#> Network (method: ngram) [directed]
#> Weights: [38.000, 861.000] | mean: 357.667
#>
#> Strongest edges (9 of 9):
#> from to weight
#> Active Active 861
#> Average Average 853
#> Active Average 324
#> Disengaged Disengaged 292
#> Average Active 285
#> Average Disengaged 266
#> Disengaged Average 233
#> Disengaged Active 67
#> Active Disengaged 38
#>
#> extract_edges(include_self = TRUE) lists every edge; extract_transition_matrix() gives the weight matrix;
#> extract_initial_probs() the initial probabilities.