knn_to_sparse: Convert a neighbor graph to a sparse matrix

View source: R/sparse.R

knn_to_sparseR Documentation

Convert a neighbor graph to a sparse matrix

Description

Rows represent observations or queries and columns represent reference observations. Set transpose = TRUE to reverse the axes. Missing neighbors (idx = 0, dist = NA) are omitted. Stored zero distances are retained. If a row contains the same neighbor more than once, the last stored distance is used.

Usage

knn_to_sparse(graph, n_reference = nrow(graph$idx), transpose = FALSE)

Arguments

graph

A neighbor graph containing idx and dist matrices.

n_reference

Number of reference observations. Supply this explicitly for query results when the reference size differs from the number of rows.

transpose

Whether to put reference observations in rows.

Value

A numeric dgCMatrix of distances.

Examples

graph <- brute_force_knn(iris[1:8, 1:4], k = 5)
knn_to_sparse(graph)

rnndescent documentation built on Nov. 26, 2026, 5:06 p.m.