Package {cooccure}


Title: Co-Occurrence Network Construction and Manipulation
Version: 0.5.0
Description: Constructs co-occurrence networks from several types of input data, such as delimited fields, long/bipartite tables, binary matrices, or wide sequences. Returns tidy edge data frames and supports optional scaling, splitting into several networks, thresholding, and subsetting. Provides eight similarity measures, including Jaccard, cosine, and association strength. Supports export to several network and file formats. Network construction and analysis methods follow Saqr, Lopez-Pernas, Conde, and Hernandez-Garcia (2024) <doi:10.1007/978-3-031-54464-4_15>.
License: MIT + file LICENSE
Encoding: UTF-8
Language: en-US
LazyData: true
Imports: graphics, grDevices, Matrix, methods, stats, utils
Suggests: igraph, cograph, Nestimate, tidygraph, testthat (≥ 3.0.0), knitr, rmarkdown, shiny, DT
Config/testthat/edition: 3
VignetteBuilder: knitr
Depends: R (≥ 3.5.0)
URL: https://github.com/mohsaqr/cooccure, https://pak.dynasite.org/cooccure/
BugReports: https://github.com/mohsaqr/cooccure/issues
Config/roxygen2/version: 8.1.1
NeedsCompilation: no
Packaged: 2026-11-17 14:15:24 UTC; mohammedsaqr
Author: Mohammed Saqr ORCID iD [aut, cre, cph], Sonsoles López-Pernas ORCID iD [aut, cph], Kamila Misiejuk [aut, cph]
Maintainer: Mohammed Saqr <saqr@saqr.me>
Repository: CRAN
Date/Publication: 2026-11-17 17:40:10 UTC

cooccure: co-occurrence networks from many kinds of data

Description

cooccure builds co-occurrence networks, in which two items are linked when they appear in the same transaction: the keywords of one article, the genres of one film, the actors of one cast, or the states of one learning session. The network shows which items tend to go together and how a field, a corpus or a set of sessions is organized around them. The weight of a link starts as the number of shared transactions; because frequent items co-occur often by chance alone, it can be normalized for item frequency by one of eight similarity measures (van Eck & Waltman, 2009), and each transaction's contribution can be counted fractionally (Perianes-Rodriguez et al., 2016) or with a position decay. One network can be built per group (split_by) or one network pooled over groups (aggregate_by).

All of this is done by one function, cooccurrence(). It reads delimited columns, long (item, transaction) tables, binary and one-hot tables, wide sequences, lists of vectors and raw event logs, with sliding windows over ordered sequences and eight scalings of the weights, and returns the network as a tidy edge list.

Results

The edge list prints with a diagnostic header. summary.cooccurrence() computes network, node and group metrics; as.data.frame.cooccurrence() returns the edge, node and group tables; plot.cooccurrence() draws a heatmap, a network or the degree distribution.

Conversion

as_matrix() returns the weight or count matrix; as_igraph(), as_tidygraph(), as_cograph() and as_netobject() convert to the graph classes of igraph, tidygraph, cograph and Nestimate. The network is undirected except for similarity = "relative", which is directed.

Data

movies, actors and actor_genres are drawn from the IMDb non-commercial datasets; demo is a small hand-built cast table. launch_app() opens an interactive explorer.

Author(s)

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

Authors:

References

van Eck, N. J., & Waltman, L. (2009). How to normalize cooccurrence data? An analysis of some well-known similarity measures. Journal of the American Society for Information Science and Technology, 60(8), 1635–1651. doi:10.1002/asi.21075

Perianes-Rodriguez, A., Waltman, L., & van Eck, N. J. (2016). Constructing bibliometric networks: A comparison between full and fractional counting. Journal of Informetrics, 10(4), 1178–1195. doi:10.1016/j.joi.2016.10.006

See Also

Useful links:


Actors and the genres of their films (IMDb, 1970-2024)

Description

actor_genres is a dataset of the genres the 624 actors of actors work in: every genre of every film they appeared in, one row per actor and genre. Used with field = "actor" and by = "genre", it links actors who work in the same genres; with the roles reversed, it links genres that share actors.

Usage

actor_genres

Format

A data frame with 2,502 rows and 2 variables:

actor

Actor name.

genre

Genre label (one row per actor-genre combination).

Source

https://data.imdb.com/non-commercial-datasets/

See Also

actors; cooccurrence().

Examples

head(actor_genres)
cooccurrence(actor_genres, field = "actor", by = "genre", similarity = "jaccard")

Actors and the films they appeared in (IMDb, 1970-2024)

Description

actors is a dataset of the 624 actors who appear in at least two of the films in movies, with one row per actor and film. The data illustrate co-occurrence from a long (item, transaction) table: actors are linked when they appear in the same film, which gives a collaboration network.

Usage

actors

Format

A data frame with 1,267 rows and 7 variables:

actor

Actor name.

tconst

IMDB title identifier linking to movies.

primaryTitle

Movie title.

startYear

Release year (integer).

decade

Release decade as a character string.

genres

Comma-separated genre labels for the linked movie.

averageRating

IMDB average user rating for the linked movie.

Source

https://data.imdb.com/non-commercial-datasets/

See Also

movies; actor_genres; cooccurrence().

Examples

head(actors)
cooccurrence(actors, field = "actor", by = "tconst", similarity = "jaccard")

Extract the tables of a co-occurrence network

Description

as.data.frame() returns a table of a co-occurrence network as a plain data frame without the network's attributes, ready for sorting, joining, plotting or writing to a file. A co-occurrence network is described by two tables: its edges, one row per pair of items with a weight and a raw count, and its nodes, one row per item with degree, strength and frequency. A network built with split_by adds a third, one row of metrics per group.

what selects the table. The edge table is the printed network; the node and group tables are those of summary.cooccurrence().

Usage

## S3 method for class 'cooccurrence'
as.data.frame(
  x,
  row.names = NULL,
  optional = FALSE,
  what = c("edges", "nodes", "groups"),
  ...
)

Arguments

x

A cooccurrence edge list from cooccurrence().

row.names, optional

Unused; present for compatibility with the base::as.data.frame() generic.

what

"edges" (default), "nodes" or "groups".

...

Ignored.

Value

A base data.frame. For what = "edges", one row per edge with columns from, to, weight and count (and group for a split_by result), in the order printed. An undirected network has one row per pair; the directed similarity = "relative" network has one row per direction. For what = "nodes" and what = "groups", the tables described in as.data.frame.summary.cooccurrence().

See Also

summary.cooccurrence(); as_matrix() for the weight matrix.

Examples

net <- cooccurrence(movies, field = "genres", sep = ",",
                    similarity = "jaccard", min_occur = 50)
as.data.frame(net)
as.data.frame(net, what = "nodes")

Extract the tables of a co-occurrence network summary

Description

as.data.frame() returns the node table or the group table of a summary.cooccurrence() object as a plain data frame, so the metrics can be sorted, filtered, joined or plotted with ordinary data-frame tools.

Usage

## S3 method for class 'summary.cooccurrence'
as.data.frame(
  x,
  row.names = NULL,
  optional = FALSE,
  what = c("nodes", "groups"),
  ...
)

Arguments

x

A summary.cooccurrence object.

row.names, optional

Unused; present for compatibility with the base::as.data.frame() generic.

what

"nodes" (default) for the node table, or "groups" for the group table of a split_by result.

...

Ignored.

Value

A base data.frame. For what = "nodes", one row per node (per node and group for a split_by result, with a leading group column), sorted by degree and strength (both decreasing) and then name, with columns node, degree (number of incident edges), strength (sum of incident edge weights), count_strength (sum of incident raw counts) and frequency (number of transactions containing the node; NA when not stored, as for aggregate_by and weighted results). For what = "groups", one row per group with columns group, n_nodes, n_edges, possible_edges, density, weight_mean and count_sum; zero rows when the network was not split.

See Also

summary.cooccurrence(); as.data.frame.cooccurrence(), which returns the same tables directly from the network.

Examples

by_decade <- cooccurrence(movies, field = "genres", sep = ",",
                          split_by = "decade", similarity = "jaccard")
as.data.frame(summary(by_decade), what = "groups")

Convert a co-occurrence network to a cograph network

Description

as_cograph() converts a co-occurrence network to a cograph_network. cograph draws and analyzes networks from a weight matrix, with layouts and styling designed for publication figures and functions for centrality and community detection. Its cograph_network class is also the base class of the networks estimated by Nestimate.

The cograph_network is built from the weight matrix returned by as_matrix(): a node table with one row per item and an edge table with one row per non-zero cell, one triangle for an undirected network and every off-diagonal cell for the directed similarity = "relative" network. The result can be passed to cograph::splot().

cograph exports its own as_cograph(). When cograph is attached after cooccure, a bare as_cograph() call resolves to the cograph version, which reads the edge data frame with its own defaults. Call cooccure::as_cograph(), or build the network with cooccurrence(..., output = "cograph"). For a result built with split_by, group names the network to convert.

Usage

as_cograph(x, ...)

## S3 method for class 'cooccurrence'
as_cograph(x, group = NULL, ...)

Arguments

x

A cooccurrence edge list from cooccurrence().

...

Ignored.

group

For a result built with split_by, the name of the group to convert. NULL (default) for an unsplit result.

Value

A list of class cograph_network holding the weight matrix (weights), a node table (one row per item: id, label, name, x, y), an edge table (one row per edge: integer from and to node ids and weight), directed (TRUE only for similarity = "relative"), and the node and edge counts.

Conditions

cooccure_missing_package when cograph is not installed; the conditions of as_matrix() for group.

See Also

as_netobject() for the Nestimate class; as_igraph(); as_matrix().

Examples

net <- cooccurrence(movies, field = "genres", sep = ",",
                    similarity = "jaccard", min_occur = 50)
if (requireNamespace("cograph", quietly = TRUE)) {
  cooccure::as_cograph(net)
}

Convert a co-occurrence network to an igraph graph

Description

as_igraph() converts a co-occurrence network to an igraph object. igraph is the most widely used general-purpose network library in R, with functions for centrality, community detection, paths and layouts; the conversion makes all of them available without re-entering the edges.

The result is a weighted graph with one vertex per item, isolates included, and one edge per row of the edge list, carrying the edge attributes weight and count. The graph is undirected, except for similarity = "relative", where each row is a directed edge and the graph is directed.

A result built with split_by holds several networks; group names the one to convert, since stacking them would create one parallel edge per group. For a tbl_graph, use as_tidygraph().

Usage

as_igraph(x, ...)

## S3 method for class 'cooccurrence'
as_igraph(x, group = NULL, ...)

Arguments

x

A cooccurrence edge list from cooccurrence(), with default or "gephi" column names.

...

Passed to igraph::graph_from_data_frame(), apart from directed and vertices, which are set here.

group

For a result built with split_by, the name of the group to convert. NULL (default) for an unsplit result.

Value

An igraph object with one vertex per item (vertex attribute name) and one edge per row of the edge list (edge attributes weight and count). Directed for similarity = "relative", undirected otherwise.

Conditions

cooccure_missing_package when igraph is not installed; cooccure_grouped_input when x was built with split_by and group is NULL; cooccure_bad_input for an unknown group.

See Also

as_tidygraph() for a tbl_graph; as_cograph() and as_netobject() for the cograph and Nestimate classes; as_matrix() for the weight matrix.

Examples

net <- cooccurrence(movies, field = "genres", sep = ",",
                    similarity = "jaccard", min_occur = 50)
if (requireNamespace("igraph", quietly = TRUE)) {
  g <- as_igraph(net)
  igraph::strength(g)
}

Extract the weight matrix of a co-occurrence network

Description

as_matrix() returns the weight matrix of a co-occurrence network built by cooccurrence(). The weight matrix is the network written as a square matrix with one row and one column per item, where a cell holds the weight of the edge between two items and the diagonal is zero. This form is what clustering, heatmaps, matrix algebra and many network packages expect, and it shows at once which item pairs never co-occur.

The cells hold the edge weights after similarity, scaling and filtering, or, with type = "raw", the number of transactions in which each pair co-occurs. The matrix agrees with the printed edge list, including any threshold or top_n filter. It is symmetric for every similarity except "relative", whose network is directed.

A result built with split_by stacks one network per group and has no single matrix, so group names the network to extract. For a graph object rather than a matrix, use as_igraph(), as_tidygraph(), as_cograph() or as_netobject().

Usage

as_matrix(x, ...)

## S3 method for class 'cooccurrence'
as_matrix(x, type = c("normalized", "raw"), group = NULL, ...)

Arguments

x

A cooccurrence edge list from cooccurrence().

...

Ignored.

type

"normalized" (default) for the edge weights, or "raw" for the co-occurrence counts.

group

For a result built with split_by, the name of the group to extract. NULL (default) for an unsplit result.

Value

A dense base numeric matrix with one row and one column per item, item names as row and column names, and a zero diagonal. Items that co-occur with nothing (isolates) keep a row of zeros. For similarity = "relative" the weight matrix is asymmetric: row i holds the weights of the edges from item i, and each non-empty row sums to 1 before filtering. The raw matrix is always symmetric.

Conditions

cooccure_grouped_input when x was built with split_by and group is NULL; cooccure_bad_input when group names no group of x, or is given for an unsplit result.

See Also

cooccurrence() to build the network; as_igraph() for a graph object; as.data.frame.cooccurrence() for the edge and node tables.

Examples

net <- cooccurrence(movies, field = "genres", sep = ",",
                    similarity = "jaccard", min_occur = 50)
as_matrix(net)
as_matrix(net, type = "raw")

# One network of a split result
by_decade <- cooccurrence(movies, field = "genres", sep = ",",
                          split_by = "decade", min_occur = 50)
as_matrix(by_decade, group = "2010s")

Convert a co-occurrence network to a Nestimate netobject

Description

as_netobject() converts a co-occurrence network to a Nestimate netobject. Nestimate estimates and compares networks of several kinds (transition, partial correlation, co-occurrence) and stores them as netobjects, which its centrality and comparison functions accept; the conversion lets a co-occurrence network sit beside networks estimated there.

The netobject has method "cooccurrence" and is built from the weight matrix returned by as_matrix(), with the same node and edge tables as as_cograph() and the similarity, scale, threshold and number of transactions recorded as parameters. It is directed only for similarity = "relative".

The netobject carries no raw data (its data element is NULL), so Nestimate functions that resample the original observations, such as Nestimate::bootstrap_network(), cannot run on it. Build the network with Nestimate::cooccurrence() for those. For a result built with split_by, group names the network to convert.

Usage

as_netobject(x, ...)

## S3 method for class 'cooccurrence'
as_netobject(x, group = NULL, ...)

Arguments

x

A cooccurrence edge list from cooccurrence().

...

Ignored.

group

For a result built with split_by, the name of the group to convert. NULL (default) for an unsplit result.

Value

A list of class c("netobject", "cograph_network") with method "cooccurrence", holding the weight matrix, a node table (one row per item), an edge table (one row per edge), directed, and the parameters used.

Conditions

cooccure_missing_package when Nestimate is not installed; the conditions of as_matrix() for group.

See Also

as_cograph(); as_igraph(); as_matrix().

Examples

net <- cooccurrence(movies, field = "genres", sep = ",",
                    similarity = "jaccard", min_occur = 50)
if (requireNamespace("Nestimate", quietly = TRUE)) {
  Nestimate::net_centrality(as_netobject(net))
}

Convert a co-occurrence network to a tidygraph

Description

as_tidygraph() converts a co-occurrence network to a tbl_graph. tidygraph represents a network as two linked tables, nodes and edges, that can be manipulated with dplyr verbs and drawn with ggraph. It suits analyses that add node or edge measures as columns and then plot them.

The conversion goes by way of as_igraph(), so the vertices, edges, attributes and direction are the same as there.

For a result built with split_by, group names the network to convert. For the plain igraph object, use as_igraph().

Usage

as_tidygraph(x, ...)

## S3 method for class 'cooccurrence'
as_tidygraph(x, group = NULL, ...)

Arguments

x

A cooccurrence edge list from cooccurrence().

...

Passed to as_igraph().

group

For a result built with split_by, the name of the group to convert. NULL (default) for an unsplit result.

Value

A tbl_graph (which also inherits from igraph) with node column name and edge columns from, to, weight and count; directed for similarity = "relative".

Conditions

cooccure_missing_package when tidygraph or igraph is not installed; the conditions of as_igraph() otherwise.

See Also

as_igraph(); as_cograph(); as_matrix().

Examples

net <- cooccurrence(movies, field = "genres", sep = ",",
                    similarity = "jaccard", min_occur = 50)
if (requireNamespace("tidygraph", quietly = TRUE) &&
    requireNamespace("igraph", quietly = TRUE)) {
  as_tidygraph(net)
}

Build a co-occurrence network

Description

cooccurrence() builds a co-occurrence network; co() is a short alias. In a co-occurrence network two items are linked when they appear in the same transaction: keywords assigned to the same article, genres of the same film, actors in the same cast, states visited in the same session or the same window of a sequence. The edge weight starts as the number of transactions shared by the two items. Because frequent items co-occur with almost everything, the counts are usually normalized by a similarity measure that compares the observed co-occurrence with the items' own frequencies (van Eck & Waltman, 2009), and transactions with many items can be down-weighted by fractional counting (Perianes-Rodriguez et al., 2016).

The transactions are read from a delimited column, a long (item, transaction) table, a binary or one-hot table, wide sequences, a list of vectors, or a raw event log. Eight similarity measures, three counting methods, eight scalings, sliding windows over ordered sequences, and per-group networks (split_by) or pooled ones (aggregate_by) are available. Every measure except "relative" gives an undirected network; "relative" divides each row by its sum, so its edges have a direction.

The network is returned as a tidy edge list with the weight (after similarity, scaling and filtering) and the raw count of each pair: it shows which items go together, how strongly, and, with split_by, how this differs across groups.

The edge list converts to a matrix with as_matrix() and to graph objects with as_igraph(), as_tidygraph(), as_cograph() and as_netobject(); summary.cooccurrence() and as.data.frame.cooccurrence() give network, node and group metrics.

Usage

cooccurrence(
  data,
  field = NULL,
  by = NULL,
  sep = NULL,
  weight_by = NULL,
  split_by = NULL,
  similarity = c("none", "jaccard", "cosine", "inclusion", "association", "dice",
    "equivalence", "relative"),
  counting = c("full", "fractional", "attention"),
  scale = NULL,
  threshold = 0,
  min_occur = 1L,
  top_n = NULL,
  output = c("default", "gephi", "igraph", "cograph", "matrix"),
  vars = NULL,
  actor = NULL,
  action = NULL,
  time = NULL,
  session = NULL,
  order = NULL,
  time_threshold = 900,
  group = NULL,
  aggregate_by = NULL,
  aggregate = c("sum", "mean", "min", "max"),
  window = NULL,
  lambda = 1,
  ...
)

co(
  data,
  field = NULL,
  by = NULL,
  sep = NULL,
  weight_by = NULL,
  split_by = NULL,
  similarity = c("none", "jaccard", "cosine", "inclusion", "association", "dice",
    "equivalence", "relative"),
  counting = c("full", "fractional", "attention"),
  scale = NULL,
  threshold = 0,
  min_occur = 1L,
  top_n = NULL,
  output = c("default", "gephi", "igraph", "cograph", "matrix"),
  vars = NULL,
  actor = NULL,
  action = NULL,
  time = NULL,
  session = NULL,
  order = NULL,
  time_threshold = 900,
  group = NULL,
  aggregate_by = NULL,
  aggregate = c("sum", "mean", "min", "max"),
  window = NULL,
  lambda = 1,
  ...
)

Arguments

data

Input data, one of:

  • a data frame with a delimited column (field and sep);

  • a long data frame with one row per item and transaction (field and by), optionally weighted (weight_by);

  • a binary (0/1 or TRUE/FALSE) data frame or matrix, detected automatically;

  • a one-hot or count table, with vars naming the indicator columns;

  • a wide sequence data frame or matrix, one row per sequence (field = "all");

  • a list of character vectors, one per transaction;

  • a raw event log (action, with actor, time, session);

  • a nestimate_data object from Nestimate::prepare().

field

The item column. For delimited input, the column split by sep (several columns are pooled per row); for long input, the item column; "all" for wide sequence data, where every column is a time point.

by

For long input, the column identifying the transaction.

sep

Separator for delimited input.

weight_by

For long input, a numeric column giving each item's weight in its transaction, so that C_{ij} = \sum_d w_{id} w_{jd} (for instance topic probabilities per document). Requires counting = "full".

split_by

A column of data. One network is built per group and the edge lists are stacked with a group column.

similarity

Normalization of the counts C_{ij} by the item frequencies f_i:

  • "none" (default): the counts;

  • "jaccard": C_{ij} / (f_i + f_j - C_{ij});

  • "cosine" (Salton): C_{ij} / \sqrt{f_i f_j};

  • "inclusion" (Simpson): C_{ij} / \min(f_i, f_j);

  • "association" (association strength): C_{ij} / (f_i f_j);

  • "dice": 2 C_{ij} / (f_i + f_j);

  • "equivalence": C_{ij}^2 / (f_i f_j);

  • "relative": C_{ij} / \sum_k C_{ik}, each row summing to 1. The only asymmetric measure: the network is directed and the edge list holds one row per direction.

counting

How each transaction contributes to a pair:

  • "full" (default): 1 per transaction containing both items;

  • "fractional": 1 / (n - 1) for a transaction of n items, so large transactions weigh less per pair;

  • "attention": \exp(-|p_i - p_j| / \lambda), decaying with the distance between the two items' positions in an ordered transaction. A repeated item keeps the position of its first occurrence.

scale

Rescaling of the weights after similarity: NULL or "none" (default), "minmax" (to [0, 1]), "log" (\log(1 + w)), "log10", "binary" (1 for every edge), "zscore", "sqrt", or "proportion" (divided by the sum).

threshold

Minimum edge weight to keep, applied after similarity and scaling, to each direction separately for "relative". The default 0 keeps every edge. A negative value keeps weights at or above it, which is useful with scale = "zscore".

min_occur

Items in fewer than min_occur transactions are dropped before counting (default 1).

top_n

Keep the top_n heaviest edges (default NULL, all). Ties at the cut are truncated. Applied per group with split_by.

output

"default" for the edge list; "gephi" for the same edges with Gephi column names; "igraph", "cograph" or "matrix" for the result of as_igraph(), as_cograph() or as_matrix(). The last three need an unsplit network.

vars

The indicator columns of a one-hot or count table, given like select in base::subset(): names, a range (A:D), positions, a negative selection (-c(id, note)) or a logical mask. Other columns are ignored. Any non-zero, non-missing value counts as presence.

actor, action, time, session, order

Columns of a raw event log: who acted, the event, its timestamp, an explicit session, and a tie-breaking order. With action, the log is cut into sessions by Nestimate::prepare() and each session becomes an ordered transaction.

time_threshold

Gap in seconds that starts a new session (default 900). Inf keeps one sequence per actor.

group

Alias for split_by.

aggregate_by

A column of data. One network is built per group and the edge weights are combined by aggregate into one network. threshold and top_n apply after combining. Cannot be combined with split_by.

aggregate

"sum" (default), "mean", "min" or "max": how aggregate_by combines weights. Counts are always summed.

window

Sliding-window size (an integer of at least 2) for ordered input (wide sequences, a list of vectors, an event log): each window of window consecutive positions is a transaction. NULL (default) uses the whole sequence.

lambda

Decay rate for counting = "attention" (default 1); larger values decay more slowly.

...

Must be empty: an unknown or misspelled argument raises an error.

Value

With output = "default", a data frame of class c("cooccurrence", "data.frame") with one row per edge, sorted by weight (largest first), and columns from and to (item names), weight (after similarity, scaling and filtering) and count (transactions containing both items; summed over groups for aggregate_by). An undirected network has one row per pair; the directed "relative" network has one row per direction. With split_by, one row per edge per group and a group column. Read the tables with as.data.frame.cooccurrence() and the matrix with as_matrix().

output = "gephi" gives the same edges with columns Source, Target, Weight, Type ("Undirected" or "Directed") and Count. "igraph", "cograph" and "matrix" return the converter's result.

Conditions

Errors inherit from cooccure_error:

With split_by or aggregate_by, a group left with no transaction is dropped; any other error in a group is raised with the group named.

References

van Eck, N. J., & Waltman, L. (2009). How to normalize cooccurrence data? An analysis of some well-known similarity measures. Journal of the American Society for Information Science and Technology, 60(8), 1635–1651. doi:10.1002/asi.21075

Perianes-Rodriguez, A., Waltman, L., & van Eck, N. J. (2016). Constructing bibliometric networks: A comparison between full and fractional counting. Journal of Informetrics, 10(4), 1178–1195. doi:10.1016/j.joi.2016.10.006

Saqr, M., Lopez-Pernas, S., Conde, M. A., & Hernandez-Garcia, A. (2024). Social network analysis: A primer, a guide and a tutorial in R. In M. Saqr & S. Lopez-Pernas (Eds.), Learning Analytics Methods and Tutorials: A Practical Guide Using R. Springer. doi:10.1007/978-3-031-54464-4_15

See Also

as.data.frame.cooccurrence() and summary.cooccurrence() for tables and metrics; as_matrix(), as_igraph(), as_cograph() and as_netobject() for conversion; plot.cooccurrence(); movies and actors for example data.

Examples

# Genres linked by the films they share (delimited column)
cooccurrence(movies, field = "genres", sep = ",", similarity = "jaccard")

# Actors linked by shared films (long table)
co(actors, field = "actor", by = "tconst", min_occur = 3)

# One network per decade
cooccurrence(movies, field = "genres", sep = ",", split_by = "decade",
             similarity = "jaccard", top_n = 3)

# A directed network: the share of each genre's links going to each other
cooccurrence(movies, field = "genres", sep = ",", similarity = "relative",
             min_occur = 100)

# Adjacent states of ordered sequences
seqs <- list(c("plan", "read", "write", "read", "review"),
             c("read", "write", "write", "review"))
cooccurrence(seqs, window = 2)

# Weighted long table (topic probabilities per document)
theta <- data.frame(
  doc   = c("d1", "d1", "d1", "d2", "d2", "d3", "d3"),
  topic = c("T1", "T2", "T3", "T1", "T3", "T2", "T3"),
  prob  = c(0.6, 0.3, 0.1, 0.4, 0.6, 0.5, 0.5)
)
cooccurrence(theta, field = "topic", by = "doc", weight_by = "prob")

# One-hot table with an id column
onehot <- data.frame(doc = c("d1", "d2", "d3"),
                     A = c(1, 0, 1), B = c(1, 1, 0), C = c(0, 1, 1))
cooccurrence(onehot, vars = A:C)

# Raw event log, cut into sessions by Nestimate

if (requireNamespace("Nestimate", quietly = TRUE)) {
  events <- data.frame(
    student = rep(c("s1", "s2"), each = 3),
    code    = c("read", "write", "read", "test", "write", "read"),
    stamp   = as.POSIXct("2026-01-01 09:00:00", tz = "UTC") +
      c(0, 60, 120, 0, 30, 90)
  )
  cooccurrence(events, actor = "student", action = "code", time = "stamp")
}



A small cast table of ten films

Description

demo is a hand-built dataset of 30 actors in 10 well-known films, each film carrying its full genre list, with one row per film, actor and genre. Every pairing of two columns gives a network: actors linked by shared films, genres linked by shared films, or actors linked by shared genres. It is small enough to check a network by hand and is the default data of launch_app().

Usage

demo

Format

A data frame with 89 rows and 3 variables:

movie

Movie title.

actor

Actor name.

genre

Genre label. Films carry every genre they belong to, so a movie contributes several rows per actor.

See Also

actors for a larger cast table; cooccurrence().

Examples

head(demo)
# Actors linked by the films they share
cooccurrence(demo, field = "actor", by = "movie", similarity = "jaccard")

# Genres linked by the films they share
cooccurrence(demo, field = "genre", by = "movie", similarity = "jaccard")

# Actors linked by the genres they share
cooccurrence(demo, field = "actor", by = "genre")

Open the interactive co-occurrence explorer

Description

launch_app() opens an interactive co-occurrence explorer: a shiny application in which a data set (the bundled demo table or an uploaded file) is turned into a network with cooccurrence() and shown as a table and a plot. The explorer is a quick way to see how the choice of items, transactions, similarity measure and filters changes a co-occurrence network before writing the analysis as code.

It requires the shiny and DT packages and an interactive session.

Usage

launch_app(...)

Arguments

...

Passed to runApp (e.g. port, launch.browser).

Value

No return value; called to run the application, which blocks the session until it is closed.

Conditions

cooccure_missing_package when shiny or DT is not installed.

See Also

cooccurrence(); demo.

Examples

if (interactive()) {
  launch_app()
}

Highly rated films with their genres (IMDb, 1970-2024)

Description

movies is a sample of 1,000 films with an IMDb rating of at least 7.0 and at least 1,000 votes, released between 1970 and 2024. Each film lists its genres in one comma-delimited column, so the data illustrate co-occurrence from a delimited field: genres are linked when they are assigned to the same film. The release decade and the rating allow one network per group.

Usage

movies

Format

A data frame with 1,000 rows and 7 variables:

tconst

IMDB title identifier (e.g. "tt0068646").

primaryTitle

Movie title.

startYear

Release year (integer).

genres

Comma-separated genre labels (e.g. "Crime,Drama").

decade

Release decade as a character string (e.g. "1970s").

averageRating

IMDB average user rating.

numVotes

Number of IMDB user votes.

Source

https://data.imdb.com/non-commercial-datasets/

See Also

actors for the casts of these films; cooccurrence().

Examples

head(movies)
cooccurrence(movies, field = "genres", sep = ",", similarity = "jaccard")

Plot a co-occurrence network

Description

plot() draws one of three displays of a co-occurrence network: a heatmap of the weight matrix (default), a network drawing through igraph, or the degree distribution as a bar chart. The heatmap shows which item pairs carry the heaviest weights and which never co-occur. The network drawing places linked items near one another. The degree distribution shows whether connectivity is concentrated on a few hub items or spread evenly.

The heatmap uses a white-to-blue scale for non-negative weights and a red-white-blue scale centered on zero when weights can be negative (scale = "zscore"); rows are the source items, which matters for the directed similarity = "relative" network.

For a result built with split_by, group names the network to draw. For publication-quality network drawings, convert with as_cograph() and use cograph::splot().

Usage

## S3 method for class 'cooccurrence'
plot(x, type = c("heatmap", "network", "degree"), group = NULL, ...)

Arguments

x

A cooccurrence edge list from cooccurrence().

type

"heatmap" (default), "network" (requires igraph), or "degree".

group

For a result built with split_by, the name of the group to draw. NULL (default) for an unsplit result.

...

Passed to graphics::image() for the heatmap, plot() on the igraph object for the network, and graphics::barplot() for the degree distribution, where they override the defaults (for instance col or main).

Value

x, invisibly and unchanged. Called for the plot drawn on the current graphics device.

Conditions

cooccure_grouped_input when x was built with split_by and group is NULL; cooccure_missing_package for type = "network" without igraph.

See Also

as_cograph() for publication network drawings; summary.cooccurrence() for the numbers behind the degree plot.

Examples

net <- cooccurrence(movies, field = "genres", sep = ",",
                    similarity = "jaccard", min_occur = 50)
plot(net)
plot(net, type = "degree")

Print a co-occurrence network

Description

print() shows a co-occurrence network as a short diagnostic header followed by the strongest edges. The header reports what is first looked at in any network before its edges are read: how many items and edges it has, how dense it is, which similarity, counting and scaling produced the weights, how many items are isolated, and which items are the hubs.

For a network built with split_by, the pooled density and degree are omitted, since they are undefined when several networks are stacked; use summary.cooccurrence() for one row of metrics per group. A directed network (similarity = "relative") is marked as such and its density is computed over ordered pairs.

Usage

## S3 method for class 'cooccurrence'
print(x, n = 10L, ...)

Arguments

x

A cooccurrence edge list from cooccurrence().

n

Number of edges to show (default 10).

...

Ignored.

Value

x, invisibly and unchanged. Called for the printed output.

See Also

summary.cooccurrence() for network, node and group metrics; as.data.frame.cooccurrence() for the edge and node tables.

Examples

net <- cooccurrence(movies, field = "genres", sep = ",",
                    similarity = "jaccard")
print(net, n = 5)

Print a co-occurrence network summary

Description

print() shows the network-level block of a summary.cooccurrence() object: the numbers of nodes, edges and possible edges, density, mean degree, isolates, transactions, the parameters used, the range and mean of the weights and counts, the top nodes by degree, and the largest groups by number of edges. For a split_by result the pooled metrics and the top-node line are omitted, since they are undefined for stacked networks.

Usage

## S3 method for class 'summary.cooccurrence'
print(x, n = 5L, ...)

Arguments

x

A summary.cooccurrence object.

n

Number of top nodes and groups to show (default 5).

...

Ignored.

Value

x, invisibly and unchanged. Called for the printed output.

See Also

summary.cooccurrence(); as.data.frame.summary.cooccurrence().

Examples

net <- cooccurrence(movies, field = "genres", sep = ",")
print(summary(net), n = 3)

Summarize a co-occurrence network

Description

summary() computes the metrics of a co-occurrence network at three levels: the network as a whole (size, density, mean degree, isolates and the distribution of edge weights and counts), each item in it (degree, strength and frequency), and, for a network built with split_by, each group. Together these show whether the network is sparse or saturated, which items are hubs, and how groups differ in size and density.

The metrics are returned as an object; printing it shows the network-level block. The node and group tables are returned as tidy data frames by as.data.frame.summary.cooccurrence(), or directly from the network with as.data.frame.cooccurrence().

For a network built with split_by, the frame stacks one network per group, so a pair can occur once per group. Pooled simple-graph metrics (density, mean_degree, possible_edges) are undefined and reported as NA; the node table has one row per node per group and the group table carries the per-group values. For the directed similarity = "relative" network, density is computed over ordered pairs and degree counts in- and out-edges.

Usage

## S3 method for class 'cooccurrence'
summary(object, ...)

Arguments

object

A cooccurrence edge list from cooccurrence().

...

Ignored.

Value

An object of class summary.cooccurrence: a list of network metrics (n_nodes, n_edges, possible_edges, density, mean_degree, isolates), the parameters used, five-number summaries of the weights and counts, a node table and, for split_by results, a group table. Read the tables with as.data.frame.summary.cooccurrence().

See Also

print.summary.cooccurrence(); as.data.frame.cooccurrence(); plot.cooccurrence() for the degree distribution.

Examples

net <- cooccurrence(movies, field = "genres", sep = ",",
                    similarity = "jaccard")
summary(net)

# The node table as a data frame
as.data.frame(summary(net), what = "nodes")