Skip to contents

Get neighbors of a node in the graph, optionally filtered by edge direction or type. This function works for all graph classes including UNKNOWN.

Usage

neighbors(
  cg,
  nodes = NULL,
  index = NULL,
  mode = c("all", "in", "out", "undirected", "bidirected", "partial")
)

neighbours(
  cg,
  nodes = NULL,
  index = NULL,
  mode = c("all", "in", "out", "undirected", "bidirected", "partial")
)

Arguments

cg

A caugi object.

nodes

A vector of node names, a vector of unquoted node names, or an expression combining these with + and c().

index

A vector of node indexes.

mode

Character; specifies which types of neighbors to return:

"all"

All neighbors (default)

"in"

Parents: nodes with directed edges pointing INTO the target node (equivalent to parents())

"out"

Children: nodes with directed edges pointing OUT from the target node (equivalent to children())

"undirected"

Nodes connected via undirected (---) edges

"bidirected"

Nodes connected via bidirected (<->) edges (equivalent to spouses() for ADMGs)

"partial"

Nodes connected via partial edges (edges with circle endpoints: o-o, o->, --o)

Not all modes are valid for all graph classes:

  • DAG: "in", "out", "all" only

  • PDAG: "in", "out", "undirected", "all"

  • UG: "undirected", "all" only

  • ADMG: "in", "out", "bidirected", "all"

  • UNKNOWN: all modes allowed

Value

Either a character vector of node names (if a single node is requested) or a list of character vectors (if multiple nodes are requested).

Examples

cg <- caugi(
  A %-->% B,
  B %-->% C,
  class = "DAG"
)
neighbors(cg, "A") # "B"
#> [1] "B"
neighbors(cg, index = 2) # "A" "C"
#> [1] "A" "C"
neighbors(cg, "B") # "A" "C"
#> [1] "A" "C"
neighbors(cg, c("B", "C"))
#> $B
#> [1] "A" "C"
#> 
#> $C
#> [1] "B"
#> 
#> $B
#> [1] "A" "C"
#>
#> $C
#> [1] "B"

# Using mode to filter by edge direction
neighbors(cg, "B", mode = "in") # "A" (parents)
#> [1] "A"
neighbors(cg, "B", mode = "out") # "C" (children)
#> [1] "C"

# Works for UNKNOWN graphs too
cg_unknown <- caugi(
  A %-->% B,
  B %---% C,
  C %o->% D,
  class = "UNKNOWN"
)
neighbors(cg_unknown, "B", mode = "in") # "A"
#> [1] "A"
neighbors(cg_unknown, "B", mode = "undirected") # "C"
#> [1] "C"
neighbors(cg_unknown, "C", mode = "partial") # "D"
#> [1] "D"