| Title: | Convert R Objects to Network Edgelists and Nodelists |
|---|---|
| Description: | Network analysis and plotting packages such as 'igraph', 'tidygraph', and 'ggraph' expect the edges and nodes of a graph as flat tables. Methods are provided to build those tables from data frames (column-pair edges chosen with 'tidyselect' semantics), tree-based model objects ('randomForest', 'tree', 'rpart', 'xgboost', 'gbm'), lists (recursive parent-child edges), and atomic vectors (sequential edges). Graphs can also be constructed in one step via as.igraph() and as_tbl_graph() methods for tree models. |
| Authors: | Jesse Brandt [aut, cre] (ORCID: <https://orcid.org/0009-0005-7462-075X>) |
| Maintainer: | Jesse Brandt <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.1.2 |
| Built: | 2026-10-17 08:40:57 UTC |
| Source: | https://github.com/jessebrandtdata/networkformat |
S3 methods for converting tree-based model objects into
tbl_graph objects. Each method wraps the
corresponding as.igraph method. These methods are
registered against the
as_tbl_graph generic from
tidygraph via delayed S3 registration and are available
whenever tidygraph is loaded.
## S3 method for class 'tree' as_tbl_graph(x, ...) ## S3 method for class 'randomForest' as_tbl_graph(x, treenum = NULL, ...) ## S3 method for class 'rpart' as_tbl_graph(x, ...) ## S3 method for class 'xgb.Booster' as_tbl_graph(x, treenum = NULL, ...) ## S3 method for class 'gbm' as_tbl_graph(x, treenum = NULL, ...)## S3 method for class 'tree' as_tbl_graph(x, ...) ## S3 method for class 'randomForest' as_tbl_graph(x, treenum = NULL, ...) ## S3 method for class 'rpart' as_tbl_graph(x, ...) ## S3 method for class 'xgb.Booster' as_tbl_graph(x, treenum = NULL, ...) ## S3 method for class 'gbm' as_tbl_graph(x, treenum = NULL, ...)
x |
An object to convert (currently |
... |
Additional arguments passed to |
treenum |
Integer vector of tree numbers to extract. Default
|
A tbl_graph object.
if (requireNamespace("rpart", quietly = TRUE) && requireNamespace("tidygraph", quietly = TRUE) && requireNamespace("igraph", quietly = TRUE)) { fit <- rpart::rpart(Sepal.Length ~ ., data = iris) tg <- tidygraph::as_tbl_graph(fit) tg }if (requireNamespace("rpart", quietly = TRUE) && requireNamespace("tidygraph", quietly = TRUE) && requireNamespace("igraph", quietly = TRUE)) { fit <- rpart::rpart(Sepal.Length ~ ., data = iris) tg <- tidygraph::as_tbl_graph(fit) tg }
S3 methods for converting tree-based model objects into
igraph graph objects. Each method calls
edgelist and nodelist internally and
handles column reconciliation so you get a ready-to-use graph.
These methods are registered against the
as.igraph generic from
igraph via delayed S3 registration and are available
whenever igraph is loaded.
## S3 method for class 'tree' as.igraph(x, ...) ## S3 method for class 'randomForest' as.igraph(x, treenum = NULL, ...) ## S3 method for class 'rpart' as.igraph(x, ...) ## S3 method for class 'xgb.Booster' as.igraph(x, treenum = NULL, ...) ## S3 method for class 'gbm' as.igraph(x, treenum = NULL, ...)## S3 method for class 'tree' as.igraph(x, ...) ## S3 method for class 'randomForest' as.igraph(x, treenum = NULL, ...) ## S3 method for class 'rpart' as.igraph(x, ...) ## S3 method for class 'xgb.Booster' as.igraph(x, treenum = NULL, ...) ## S3 method for class 'gbm' as.igraph(x, treenum = NULL, ...)
x |
An object to convert ( |
... |
Additional arguments passed to methods. |
treenum |
Integer vector of tree numbers to extract. Default
|
An igraph object. For
randomForest with multiple trees, the graph contains
disconnected components (one per tree) and a treenum
vertex/edge attribute.
if (requireNamespace("rpart", quietly = TRUE) && requireNamespace("igraph", quietly = TRUE)) { fit <- rpart::rpart(Sepal.Length ~ ., data = iris) g <- igraph::as.igraph(fit) igraph::vcount(g) igraph::ecount(g) }if (requireNamespace("rpart", quietly = TRUE) && requireNamespace("igraph", quietly = TRUE)) { fit <- rpart::rpart(Sepal.Length ~ ., data = iris) g <- igraph::as.igraph(fit) igraph::vcount(g) igraph::ecount(g) }
A small dataset of university courses with prerequisite and
crosslisting relationships, suitable for demonstrating edgelist()
and nodelist().
coursescourses
A data.frame with 13 rows and 7 columns:
Department code (STAT, MATH, DATA, CS)
Course identifier, used as node ID
Prerequisite course (NA if none)
Second prerequisite course (NA if none)
Crosslisted equivalent course (NA if none)
Number of credit hours (integer)
Course level: 100, 200, or 300 (integer)
# Prerequisite edgelist (course -> prereq) edgelist(courses, source_cols = course, target_cols = prereq) # Node list with course as ID column nodelist(courses, id_col = course)# Prerequisite edgelist (course -> prereq) edgelist(courses, source_cols = course, target_cols = prereq) # Node list with course as ID column nodelist(courses, id_col = course)
Generic function to extract a network edgelist from various object types.
Methods exist for atomic vectors (sequential edges), data frames
(column-pair edges), lists (recursive parent-child edges), and tree-based
model objects (randomForest, tree, rpart,
xgb.Booster, gbm).
The specific columns returned depend on the input type.
edgelist(input_object, ...)edgelist(input_object, ...)
input_object |
An object to extract an edgelist from |
... |
Additional arguments passed to specific methods |
A data.frame representing an edgelist. The specific columns depend on the input object type.
# Vector --- sequential edges edgelist(c("A", "B", "C", "D")) # Data.frame example using bundled dataset edgelist(courses, source_cols = course, target_cols = prereq) # RandomForest example if (requireNamespace("randomForest", quietly = TRUE)) { rf <- randomForest::randomForest(Species ~ ., data = iris, ntree = 5) edges_rf <- edgelist(rf) head(edges_rf) } # Tree example if (requireNamespace("tree", quietly = TRUE)) { tr <- tree::tree(Species ~ ., data = iris) edges_tr <- edgelist(tr) head(edges_tr) }# Vector --- sequential edges edgelist(c("A", "B", "C", "D")) # Data.frame example using bundled dataset edgelist(courses, source_cols = course, target_cols = prereq) # RandomForest example if (requireNamespace("randomForest", quietly = TRUE)) { rf <- randomForest::randomForest(Species ~ ., data = iris, ntree = 5) edges_rf <- edgelist(rf) head(edges_rf) } # Tree example if (requireNamespace("tree", quietly = TRUE)) { tr <- tree::tree(Species ~ ., data = iris) edges_tr <- edgelist(tr) head(edges_tr) }
Converts a data.frame to network edgelist format by specifying which columns represent source and target nodes. This is useful for creating edgelists from tabular data where node relationships are stored in columns.
## S3 method for class 'data.frame' edgelist( input_object, source_cols = 1, target_cols = 2, attr_cols = NULL, na.rm = TRUE, symmetric_cols = NULL, dedupe = TRUE, weights = FALSE, ... )## S3 method for class 'data.frame' edgelist( input_object, source_cols = 1, target_cols = 2, attr_cols = NULL, na.rm = TRUE, symmetric_cols = NULL, dedupe = TRUE, weights = FALSE, ... )
input_object |
A data.frame containing network information |
source_cols |
Column(s) for source nodes (default: 1). Accepts
tidyselect
expressions: bare names, strings, numeric indices, or helpers like
|
target_cols |
Column(s) for target nodes (default: 2). Same syntax as
|
attr_cols |
Columns to carry as edge attributes (default: |
na.rm |
Logical; if |
symmetric_cols |
Target column names that represent undirected
(symmetric) relationships. When non- |
dedupe |
Logical; if |
weights |
Logical; if |
... |
Additional arguments (currently unused) |
A data.frame with columns:
Source node values
Target node values
Name of the original column each source value came from
Name of the original column each target value came from
(only when symmetric_cols is provided) Logical:
FALSE for edges from symmetric target columns, TRUE
otherwise
(only when weights = TRUE) Integer count of how
many times each unique (from, to) pair occurred
Additional attribute columns selected by attr_cols
# Basic usage --- all non-source/target columns kept by default edgelist(courses, source_cols = course, target_cols = prereq) # Multiple target columns --- to_col identifies the relationship type edgelist(courses, source_cols = course, target_cols = c(prereq, crosslist)) # Keep only the edgelist (no attribute columns) edgelist(courses, source_cols = course, target_cols = prereq, attr_cols = c()) # Select specific attribute columns edgelist(courses, source_cols = course, target_cols = prereq, attr_cols = c(dept, credits)) # NA removal (default) vs preservation edgelist(courses, source_cols = course, target_cols = c(prereq, crosslist)) edgelist(courses, source_cols = course, target_cols = c(prereq, crosslist), na.rm = FALSE) # Mark symmetric (undirected) target columns edgelist(courses, source_cols = course, target_cols = c(prereq, crosslist), symmetric_cols = crosslist)# Basic usage --- all non-source/target columns kept by default edgelist(courses, source_cols = course, target_cols = prereq) # Multiple target columns --- to_col identifies the relationship type edgelist(courses, source_cols = course, target_cols = c(prereq, crosslist)) # Keep only the edgelist (no attribute columns) edgelist(courses, source_cols = course, target_cols = prereq, attr_cols = c()) # Select specific attribute columns edgelist(courses, source_cols = course, target_cols = prereq, attr_cols = c(dept, credits)) # NA removal (default) vs preservation edgelist(courses, source_cols = course, target_cols = c(prereq, crosslist)) edgelist(courses, source_cols = course, target_cols = c(prereq, crosslist), na.rm = FALSE) # Mark symmetric (undirected) target columns edgelist(courses, source_cols = course, target_cols = c(prereq, crosslist), symmetric_cols = crosslist)
When called on an atomic vector (character, numeric, integer, logical,
factor), creates a sequential edgelist connecting each element to the next:
element i is connected to element i + 1. For all other
unsupported types, an informative error is raised.
## Default S3 method: edgelist(input_object, weights = FALSE, ...)## Default S3 method: edgelist(input_object, weights = FALSE, ...)
input_object |
An atomic vector, or an object for which no specific edgelist method exists. |
weights |
Logical; if |
... |
Additional arguments (currently unused) |
A data.frame with columns from and to (and
weight when weights = TRUE). For unsupported types, an
error is raised.
# Character vector edgelist(c("A", "B", "C", "D")) # Numeric vector edgelist(1:5) # With duplicate counting edgelist(c("A", "B", "A", "B", "C"), weights = TRUE) # Unsupported type try(edgelist(as.formula(y ~ x)))# Character vector edgelist(c("A", "B", "C", "D")) # Numeric vector edgelist(1:5) # With duplicate counting edgelist(c("A", "B", "A", "B", "C"), weights = TRUE) # Unsupported type try(edgelist(as.formula(y ~ x)))
Converts a gbm model object into a network edgelist representation
using pretty.gbm.tree(). Missing-sentinel nodes (the phantom
routing nodes gbm creates for NA handling) are excluded — only real
LeftNode/RightNode edges are returned.
## S3 method for class 'gbm' edgelist(input_object, treenum = NULL, ...)## S3 method for class 'gbm' edgelist(input_object, treenum = NULL, ...)
input_object |
A gbm model object from the gbm package |
treenum |
Integer vector of 1-based tree numbers to extract
(default: |
... |
Additional arguments (currently unused) |
Node IDs are 0-based integers per tree. For models with
num.classes > 1 (multinomial), physical trees are stored as
n.trees * num.classes entries; treenum indexes into
this flat sequence.
A data.frame with the following columns:
Parent node ID (0-based integer)
Child node ID (0-based integer)
0-based variable index
Split threshold for continuous variables, or
c.splits index for categorical variables
Prediction value at the child node
1-based tree number
Human-readable variable name
if (requireNamespace("gbm", quietly = TRUE)) { set.seed(1) fit <- gbm::gbm(mpg ~ ., data = mtcars, distribution = "gaussian", n.trees = 5, interaction.depth = 3, n.minobsinnode = 3) el <- edgelist(fit) head(el) # Single tree el1 <- edgelist(fit, treenum = 1) }if (requireNamespace("gbm", quietly = TRUE)) { set.seed(1) fit <- gbm::gbm(mpg ~ ., data = mtcars, distribution = "gaussian", n.trees = 5, interaction.depth = 3, n.minobsinnode = 3) el <- edgelist(fit) head(el) # Single tree el1 <- edgelist(fit, treenum = 1) }
Recursively traverses a nested list structure, producing a parent-child edgelist. Each element of the list becomes a node; nested lists create deeper edges. Path-style IDs ensure unique node names even when element names repeat at different levels.
## S3 method for class 'list' edgelist(input_object, name_root = "root", max_depth = NULL, ...)## S3 method for class 'list' edgelist(input_object, name_root = "root", max_depth = NULL, ...)
input_object |
A list (or S3 object falling through to this method). |
name_root |
Character; label for the root node.
Defaults to |
max_depth |
Integer or |
... |
Additional arguments (currently unused). |
When called on an S3 object that has no dedicated edgelist method
(e.g. an lm object), the object is treated as a plain list and a
diagnostic message is emitted. To force structural decomposition of an
object that has its own method (e.g. a tree), use
edgelist(unclass(x)).
A data.frame with columns from, to, and depth
(integer depth of the child node, root children are depth 1).
An empty list returns a zero-row data.frame with the same columns.
edgelist(list(a = 1, b = list(c = 2, d = 3))) # Unnamed elements use positional indices edgelist(list(1, 2, list(3, 4))) # Limit depth (root = 0, children = 1, ...) edgelist(list(a = list(b = list(c = 1))), max_depth = 2)edgelist(list(a = 1, b = list(c = 2, d = 3))) # Unnamed elements use positional indices edgelist(list(1, 2, list(3, 4))) # Limit depth (root = 0, children = 1, ...) edgelist(list(a = list(b = list(c = 1))), max_depth = 2)
Converts a randomForest model object into a network edgelist representation by extracting parent-child relationships from one or more trees in the forest. Each edge represents a split in the decision tree, with additional attributes including split variable, split point, and prediction values.
## S3 method for class 'randomForest' edgelist(input_object, treenum = NULL, ...)## S3 method for class 'randomForest' edgelist(input_object, treenum = NULL, ...)
input_object |
A randomForest model object from the randomForest package |
treenum |
Integer vector of tree numbers to extract (default:
|
... |
Additional arguments (currently unused) |
A data.frame with the following columns:
Parent node index within the tree
Child node index (left or right daughter)
Numeric index of the variable used for splitting
Threshold value for the split
Prediction value at the child node
Branch direction: "left" or "right"
Tree number within the forest
Character vector with human-readable variable names
if (requireNamespace("randomForest", quietly = TRUE)) { set.seed(12) rf_model <- randomForest::randomForest( Species ~ ., data = iris, ntree = 5, maxnodes = 10 ) # Extract all trees rf_edges <- edgelist(rf_model) head(rf_edges) # Extract specific trees rf_edges_1 <- edgelist(rf_model, treenum = 1) rf_edges_13 <- edgelist(rf_model, treenum = c(1, 3)) }if (requireNamespace("randomForest", quietly = TRUE)) { set.seed(12) rf_model <- randomForest::randomForest( Species ~ ., data = iris, ntree = 5, maxnodes = 10 ) # Extract all trees rf_edges <- edgelist(rf_model) head(rf_edges) # Extract specific trees rf_edges_1 <- edgelist(rf_model, treenum = 1) rf_edges_13 <- edgelist(rf_model, treenum = c(1, 3)) }
Converts an rpart model object into a network edgelist representation.
The rpart package uses binary heap numbering for node IDs
(root = 1, left child of k = 2k, right child of k = 2k + 1), so
parent-child edges are derived directly from the node IDs in
rownames(input_object$frame).
## S3 method for class 'rpart' edgelist(input_object, ...)## S3 method for class 'rpart' edgelist(input_object, ...)
input_object |
An rpart model object from the rpart package |
... |
Additional arguments (currently unused) |
Edge labels come from labels(input_object, collapse = TRUE),
which correctly handles the ncat sign that controls split
direction (left child does not always get "<").
A data.frame with the following columns:
Parent node ID (binary heap index)
Child node ID (binary heap index)
Split condition label from labels()
Variable name used for the split
Operator: "<" or ">=" for numeric splits,
NA for categorical splits
Numeric threshold for the split (NA for
categorical splits)
if (requireNamespace("rpart", quietly = TRUE)) { fit <- rpart::rpart(Species ~ ., data = iris) el <- edgelist(fit) head(el) # Parsed split components el[, c("split_var", "split_op", "split_point")] }if (requireNamespace("rpart", quietly = TRUE)) { fit <- rpart::rpart(Species ~ ., data = iris) el <- edgelist(fit) head(el) # Parsed split components el[, c("split_var", "split_op", "split_point")] }
Converts a tree model object (from the tree package) into a network edgelist
representation. The tree package uses binary heap numbering for node IDs
(root = 1, left child of k = 2k, right child of k = 2k + 1), so
parent-child edges are derived directly from the node IDs in
rownames(input_object$frame).
## S3 method for class 'tree' edgelist(input_object, ...)## S3 method for class 'tree' edgelist(input_object, ...)
input_object |
A tree model object from the tree package |
... |
Additional arguments (currently unused) |
A data.frame with the following columns:
Parent node ID (binary heap index)
Child node ID (binary heap index)
Split condition label (variable and threshold)
Variable name used for the split
Operator: "<" or ">" for numeric splits,
NA for categorical splits
Numeric threshold for the split (NA for
categorical splits)
if (requireNamespace("tree", quietly = TRUE)) { # Fit a classification tree tree_model <- tree::tree(Species ~ ., data = iris) # Extract edgelist tree_edges <- edgelist(tree_model) head(tree_edges) # Parsed split components tree_edges[, c("split_var", "split_op", "split_point")] }if (requireNamespace("tree", quietly = TRUE)) { # Fit a classification tree tree_model <- tree::tree(Species ~ ., data = iris) # Extract edgelist tree_edges <- edgelist(tree_model) head(tree_edges) # Parsed split components tree_edges[, c("split_var", "split_op", "split_point")] }
Converts an xgboost model object into a network edgelist representation
using xgb.model.dt.tree(). Each edge connects a split node to
one of its two children (yes/no branches). Node IDs are globally unique
strings in "Tree-Node" format (e.g., "0-3").
## S3 method for class 'xgb.Booster' edgelist(input_object, treenum = NULL, ...)## S3 method for class 'xgb.Booster' edgelist(input_object, treenum = NULL, ...)
input_object |
An xgboost model object ( |
treenum |
Integer vector of 1-based tree numbers to extract
(default: |
... |
Additional arguments (currently unused) |
A data.frame with the following columns:
Parent node ID string ("Tree-Node" format)
Child node ID string
Name of the split variable (or 0-based index string when feature names are absent)
Numeric split threshold
Information gain at the split
Number of observations covered
1-based tree number
if (requireNamespace("xgboost", quietly = TRUE)) { data(agaricus.train, package = "xgboost") bst <- xgboost::xgboost( x = agaricus.train$data, y = factor(agaricus.train$label), max_depth = 2, nrounds = 2, nthreads = 1 ) el <- edgelist(bst) head(el) }if (requireNamespace("xgboost", quietly = TRUE)) { data(agaricus.train, package = "xgboost") bst <- xgboost::xgboost( x = agaricus.train$data, y = factor(agaricus.train$label), max_depth = 2, nrounds = 2, nthreads = 1 ) el <- edgelist(bst) head(el) }
Generic function to extract a node list (with attributes) from various
object types including atomic vectors (unique values with frequencies),
data frames, lists (recursive node decomposition), and tree models
(randomForest, tree, rpart, xgb.Booster,
gbm). The node list provides
metadata about each node in the network.
nodelist(input_object, ...)nodelist(input_object, ...)
input_object |
An object containing node information (vector, data.frame, tree model, etc.) |
... |
Additional arguments passed to specific methods |
A data.frame where the first column is the node ID and subsequent columns contain node attributes
# Vector --- unique values with frequency counts nodelist(c("A", "B", "A", "C")) # Node list with course as ID (column 2) nodelist(courses, id_col = 2)# Vector --- unique values with frequency counts nodelist(c("A", "B", "A", "C")) # Node list with course as ID (column 2) nodelist(courses, id_col = 2)
Reorders a data.frame to place the ID column first, creating a proper node list format. All other columns are treated as node attributes.
## S3 method for class 'data.frame' nodelist(input_object, id_col = 1, ...)## S3 method for class 'data.frame' nodelist(input_object, id_col = 1, ...)
input_object |
A data.frame containing node information |
id_col |
Column for the node ID (default: 1). Accepts tidyselect expressions: a bare name, string, or numeric index. |
... |
Additional arguments (currently unused) |
A data.frame with the ID column first, followed by all attribute columns
# Default: first column (dept) is ID nodelist(courses) # Use bare column name nodelist(courses, id_col = course) # Numeric index still works nodelist(courses, id_col = 2)# Default: first column (dept) is ID nodelist(courses) # Use bare column name nodelist(courses, id_col = course) # Numeric index still works nodelist(courses, id_col = 2)
When called on an atomic vector (character, numeric, integer, logical,
factor), returns the unique values as a node list with a name
column (preserving order of first appearance) and an n column
giving the frequency of each value. For all other unsupported types,
an informative error is raised.
## Default S3 method: nodelist(input_object, ...)## Default S3 method: nodelist(input_object, ...)
input_object |
An atomic vector, or an object for which no specific nodelist method exists. |
... |
Additional arguments (currently unused) |
A data.frame with columns name (unique values in order of
first appearance) and n (frequency count). For unsupported types,
an error is raised.
# Character vector nodelist(c("A", "B", "C", "A", "B")) # Numeric vector nodelist(c(1, 2, 3, 2, 1)) # Unsupported type try(nodelist(as.formula(y ~ x)))# Character vector nodelist(c("A", "B", "C", "A", "B")) # Numeric vector nodelist(c(1, 2, 3, 2, 1)) # Unsupported type try(nodelist(as.formula(y ~ x)))
Extracts node-level attributes from a gbm model via
pretty.gbm.tree(). Missing-sentinel nodes are excluded by
keeping only nodes reachable through LeftNode/RightNode
edges from the root.
## S3 method for class 'gbm' nodelist(input_object, treenum = NULL, ...)## S3 method for class 'gbm' nodelist(input_object, treenum = NULL, ...)
input_object |
A gbm model object from the gbm package |
treenum |
Integer vector of 1-based tree numbers to extract
(default: |
... |
Additional arguments (currently unused) |
A data.frame with one row per real node and the following columns:
0-based node ID within the tree
Logical: TRUE for terminal nodes
0-based variable index (NA for leaves)
Variable name (NA for leaves)
Split threshold (NA for leaves)
Prediction value at the node
Impurity reduction from the split (0 for leaves);
per-node variable importance from ErrorReduction
Number of training observations reaching the node,
from Weight
1-based tree number
Display label: "<var>\n< <threshold>" for
splits, rounded prediction for leaves
if (requireNamespace("gbm", quietly = TRUE)) { set.seed(1) fit <- gbm::gbm(mpg ~ ., data = mtcars, distribution = "gaussian", n.trees = 5, interaction.depth = 3, n.minobsinnode = 3) nl <- nodelist(fit) head(nl) }if (requireNamespace("gbm", quietly = TRUE)) { set.seed(1) fit <- gbm::gbm(mpg ~ ., data = mtcars, distribution = "gaussian", n.trees = 5, interaction.depth = 3, n.minobsinnode = 3) nl <- nodelist(fit) head(nl) }
Recursively traverses a nested list structure, producing one row per node with metadata about each element.
## S3 method for class 'list' nodelist(input_object, name_root = "root", max_depth = NULL, ...)## S3 method for class 'list' nodelist(input_object, name_root = "root", max_depth = NULL, ...)
input_object |
A list (or S3 object falling through to this method). |
name_root |
Character; label for the root node.
Defaults to |
max_depth |
Integer or |
... |
Additional arguments (currently unused). |
When called on an S3 object that has no dedicated nodelist method,
the object is treated as a plain list and a diagnostic message is emitted.
To force structural decomposition of an object that has its own method
(e.g. a tree), use nodelist(unclass(x)).
A data.frame with columns name (path-style ID),
depth (integer), type (character class of the element),
n_children (integer, 0 for leaves), and label
(element name or positional index).
An empty list returns a one-row data.frame for the root node only.
nodelist(list(a = 1, b = list(c = 2, d = 3))) # Unnamed elements nodelist(list(1, 2, list(3, 4)))nodelist(list(a = 1, b = list(c = 2, d = 3))) # Unnamed elements nodelist(list(1, 2, list(3, 4)))
Extracts node-level attributes from every tree in a
randomForest model.
Node IDs match the from/to indices produced by
edgelist.randomForest, so the two outputs can be
passed directly to igraph::graph_from_data_frame() (after
filtering to a single treenum).
## S3 method for class 'randomForest' nodelist(input_object, treenum = NULL, ...)## S3 method for class 'randomForest' nodelist(input_object, treenum = NULL, ...)
input_object |
A randomForest model object from the randomForest package |
treenum |
Integer vector of tree numbers to extract (default:
|
... |
Additional arguments (currently unused) |
A data.frame with one row per node (across all trees) and the following columns:
Integer node ID within the tree (matches edgelist from/to)
Logical: TRUE for terminal nodes
Numeric index of the split variable (NA for
leaves)
Name of the split variable (NA for
leaves)
Split threshold (NA for leaves)
Predicted value (numeric for regression, integer class index for classification)
Integer identifying which tree the node belongs to
Display label: "<var>\n< <threshold>" for
internal nodes, predicted class name (classification) or numeric
value (regression) for leaves
if (requireNamespace("randomForest", quietly = TRUE)) { set.seed(12) rf <- randomForest::randomForest(Species ~ ., data = iris, ntree = 3) nodes <- nodelist(rf) head(nodes) # Extract a single tree nodes1 <- nodelist(rf, treenum = 1) }if (requireNamespace("randomForest", quietly = TRUE)) { set.seed(12) rf <- randomForest::randomForest(Species ~ ., data = iris, ntree = 3) nodes <- nodelist(rf) head(nodes) # Extract a single tree nodes1 <- nodelist(rf, treenum = 1) }
Extracts node-level attributes from an rpart model object.
Node IDs are the binary heap indices from rownames(input_object$frame)
and match the from/to values produced by
edgelist.rpart, so the two outputs can be passed directly to
igraph::graph_from_data_frame().
## S3 method for class 'rpart' nodelist(input_object, ...)## S3 method for class 'rpart' nodelist(input_object, ...)
input_object |
An rpart model object from the rpart package |
... |
Additional arguments (currently unused) |
A data.frame with one row per node and the following columns:
Integer node ID (binary heap index, matches edgelist from/to)
Split variable name, or "<leaf>" for terminal nodes
Number of observations routed to this node
Deviance (impurity) at this node
Predicted value (numeric for regression, character class label for classification)
Logical: TRUE for terminal nodes
Integer tree depth (root = 0)
Weighted observation count
CP pruning parameter at this node
Number of competing splits considered
Number of surrogate splits used
Numeric deviance reduction from this node's split
(NA for leaves)
(Classification only) One column per class with the count of
observations of that class at the node, named n_<classname>.
Class names are sanitized via make.names() and lowercased.
(Classification only) One column per class with the
class probability at that node, named prob_<classname>.
Class names are sanitized via make.names() and lowercased.
(Classification only) Proportion of training data reaching this node
Display label: "<var>\nn=<n>" for internal nodes,
"<yval>\nn=<n>" for leaves
if (requireNamespace("rpart", quietly = TRUE)) { fit <- rpart::rpart(Species ~ Sepal.Length + Sepal.Width, data = iris) nodelist(fit) # Labels ready for plotting nodelist(fit)$label }if (requireNamespace("rpart", quietly = TRUE)) { fit <- rpart::rpart(Species ~ Sepal.Length + Sepal.Width, data = iris) nodelist(fit) # Labels ready for plotting nodelist(fit)$label }
Extracts node-level attributes from a tree model object.
Node IDs are the binary heap indices from rownames(input_object$frame)
and match the from/to values produced by
edgelist.tree, so the two outputs can be passed directly to
igraph::graph_from_data_frame().
## S3 method for class 'tree' nodelist(input_object, ...)## S3 method for class 'tree' nodelist(input_object, ...)
input_object |
A tree model object from the tree package |
... |
Additional arguments (currently unused) |
A data.frame with one row per node and the following columns:
Integer node ID (binary heap index, matches edgelist from/to)
Split variable name, or "<leaf>" for terminal nodes
Number of observations routed to this node
Deviance (impurity) at this node
Predicted value (numeric for regression, character for classification)
Logical: TRUE for terminal nodes
Integer tree depth (root = 0)
Numeric deviance reduction from this node's split
(NA for leaves)
(Classification only) One column per class with the
class probability at that node, named prob_<classname>.
Class names are sanitized via make.names() and lowercased.
Display label: "<var>\nn=<n>" for internal nodes,
"<yval>\nn=<n>" for leaves
if (requireNamespace("tree", quietly = TRUE)) { tr <- tree::tree(Species ~ Sepal.Length + Sepal.Width, data = iris) nodelist(tr) # Labels ready for plotting nodelist(tr)$label }if (requireNamespace("tree", quietly = TRUE)) { tr <- tree::tree(Species ~ Sepal.Length + Sepal.Width, data = iris) nodelist(tr) # Labels ready for plotting nodelist(tr)$label }
Extracts node-level attributes from an xgboost model via
xgb.model.dt.tree(). Node IDs are globally unique strings
in "Tree-Node" format and match the from/to
columns produced by edgelist.xgb.Booster.
## S3 method for class 'xgb.Booster' nodelist(input_object, treenum = NULL, ...)## S3 method for class 'xgb.Booster' nodelist(input_object, treenum = NULL, ...)
input_object |
An xgboost model object ( |
treenum |
Integer vector of 1-based tree numbers to extract
(default: |
... |
Additional arguments (currently unused) |
A data.frame with one row per node and the following columns:
Node ID string ("Tree-Node" format, matches
edgelist from/to)
Logical: TRUE for leaf nodes
Split variable name (NA for leaves)
Split threshold (NA for leaves)
Information gain for splits, leaf score for leaves
Cover (sum of second-order gradient)
Node ID ("Tree-Node" format) where observations
with missing values are routed; NA for leaves
1-based tree number
Display label: "<feature>\n< <threshold>" for
splits, rounded leaf score for leaves
if (requireNamespace("xgboost", quietly = TRUE)) { data(agaricus.train, package = "xgboost") bst <- xgboost::xgboost( x = agaricus.train$data, y = factor(agaricus.train$label), max_depth = 2, nrounds = 2, nthreads = 1 ) nl <- nodelist(bst) head(nl) }if (requireNamespace("xgboost", quietly = TRUE)) { data(agaricus.train, package = "xgboost") bst <- xgboost::xgboost( x = agaricus.train$data, y = factor(agaricus.train$label), max_depth = 2, nrounds = 2, nthreads = 1 ) nl <- nodelist(bst) head(nl) }