Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: New largest_component() returns the largest connected component #786

Merged
merged 10 commits into from
May 22, 2023
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -574,6 +574,7 @@ export(laplacian_matrix)
export(largest.cliques)
export(largest.independent.vertex.sets)
export(largest_cliques)
export(largest_component)
export(largest_ivs)
export(largest_weighted_cliques)
export(last_cit)
Expand Down
40 changes: 40 additions & 0 deletions R/components.R
Original file line number Diff line number Diff line change
Expand Up @@ -206,3 +206,43 @@ bridges <- bridges_impl
#' @family components
#' @export
biconnected_components <- biconnected_components_impl


#' Find the largest connected component of a graph
#'
#' This function returns the largest connected component of a graph. In case of
#' a tie, the first component by vertex ID order is returned. Vertex IDs from
#' the original graph are not retained in the returned graph.
#'
## #' @rdname components
## #' @family components
#' @param graph The original graph.
#' @param mode Passed to `components()`. Ignored if `graph` is undirected.
#' @returns The largest connected component of the graph.
#' @seealso [components()], [induced_subgraph()]
#' @export
#'
#' @examples
#' N <- 8
#' p <- .2
#' g <- sample_gnp(N, p, directed = TRUE)
#' V(g)$color <- 1:N
#' plot(g)
#' plot(largest_component(g))
#' plot(largest_component(g, mode = "strong"))
largest_component <- function(graph, mode = c("weak", "strong")) {
if (!is_igraph(graph)) {
stop("Not a graph object")
}

if (is_directed(graph)) {
comps <- components(graph, mode = mode)
} else {
comps <- components(graph)
}
ngmaclaren marked this conversation as resolved.
Show resolved Hide resolved

lcc_id <- which.max(comps$csize)
vids <- V(graph)[comps$membership == lcc_id]

induced_subgraph(graph, vids)
}
33 changes: 33 additions & 0 deletions man/largest_component.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.