6f3a34d7dcad13cb351ee238bf1dc7667872b138
[nngd.git] / R / nng.R
1 #' Compute the nearest-neighbors graph + pairwise distances.
2 #'
3 #' This is just a wrapper around C++/Rcpp function.
4 #'
5 #' @param data data.frame or matrix.
6 #' @param k Number of neighbors at each point.
7 #' @param mutual Whether or not to build mutual kNN graph.
8 #'
9 #' @return A list with $graph and $distances.
10 #'
11 #' @export
12 nng <- function(data, k=ceil(sqrt(nrow(data))), mutual=TRUE)
13 {
14 mdata <- data
15 if (is.data.frame(data)) mdata <- as.matrix(data)
16 res <- findNeighbors(mdata, k, mutual)
17 list(graph = igraph::graph_from_edgelist(t(res$edges), directed = !mutual),
18 distances = sqrt(res$euc_dists))
19 }