Learn R Programming

DiagrammeR (version 0.8.4)

select_nodes_in_neighborhood: Select nodes based on a walk distance from a specified node

Description

Select those nodes in the neighborhood of nodes connected a specified distance from an initial node.

Usage

select_nodes_in_neighborhood(graph, node, distance, set_op = "union")

Arguments

graph
a graph object of class dgr_graph that is created using create_graph.
node
the node from which the traversal will originate.
distance
the maximum number of steps from the node for inclusion in the selection.
set_op
the set operation to perform upon consecutive selections of graph nodes. This can either be as a union (the default), as an intersection of selections with intersect, or, as a difference on the previous selection, if it exists.

Value

a graph object of class dgr_graph.

Examples

Run this code
library(magrittr)

# Create a graph with a tree structure that's
# 4 levels deep (begins with node `1`, branching
# by 3 nodes at each level); the resulting graph
# contains 40 nodes, numbered `1` through `40`
graph <-
  create_graph(graph_attrs = 'layout = twopi') %>%
  add_node("A") %>% select_nodes %>%
  add_n_nodes_ws(3, "from", "B") %>%
  clear_selection %>%
  select_nodes("type", "B") %>%
  add_n_nodes_ws(3, "from", "C") %>%
  clear_selection %>%
  select_nodes("type", "C") %>%
  add_n_nodes_ws(3, "from", "D") %>%
  clear_selection

# Create a graph selection by selecting nodes
# in the neighborhood of node `1`, where the
# neighborhood is limited by nodes that are 1
# connection away from node `1`
graph %<>%
  select_nodes_in_neighborhood(
    node = 1,
    distance = 1)

# Get the selection of nodes
graph %>% get_selection
#> $nodes
#> [1] "1" "2" "3" "4"

# Perform another selection of nodes, this time
# with a neighborhood spanning 2 nodes from node `1`
graph %<>%
  clear_selection %>%
  select_nodes_in_neighborhood(
    node = 1,
    distance = 2)

# Get the selection of nodes
graph %>% get_selection
#> $nodes
#> [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"
#> [10] "10" "11" "12" "13"

# Perform a final selection of nodes, using
# `distance = 3`, this effectively selects all 40
# nodes in this graph
graph %<>%
  clear_selection %>%
  select_nodes_in_neighborhood(
    node = 1,
    distance = 3)

# Get a count of the nodes selected to verify
# that all 40 nodes have indeed been selected
graph %>% get_selection %>% unlist %>% length
#> [1] 40

Run the code above in your browser using DataLab