Skip to contents

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.

Usage

# 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, ...)

Arguments

x

An object to convert (tree, randomForest, rpart, xgb.Booster, or gbm).

...

Additional arguments passed to methods.

treenum

Integer vector of tree numbers to extract. Default NULL returns all trees combined into one graph with disconnected components. Pass a single integer (e.g. 1) to extract one tree.

Value

An igraph object. For randomForest with multiple trees, the graph contains disconnected components (one per tree) and a treenum vertex/edge attribute.

Examples

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)
}
#> [1] 12