add_nodes_from_df_cols {DiagrammeR} | R Documentation |
Add new nodes to a graph object of
class dgr_graph
using distinct values from
one or more columns in a data frame. The values will
serve as node labels and the number of nodes added
depends on the number of distinct values found in
the specified columns.
add_nodes_from_df_cols(graph, df, columns, type = NULL, keep_duplicates = FALSE)
graph |
a graph object of class
|
df |
a data frame from which values will be taken as new nodes for the graph. |
columns |
a character vector of column names
or a numeric vector of column numbers for the
data frame supplied in |
type |
an optional, single-length character vector that provides a group identifier for the nodes to be added to the graph. |
keep_duplicates |
an option to exclude
incoming nodes where the any labels (i.e.,
values found in columns of the specified
|
a graph object of class dgr_graph
.
# Create a simple graph graph <- create_graph() %>% add_path(2) # Create a data frame from which several # columns have values designated as graph nodes df <- data.frame( col_1 = c("f", "p", "q"), col_2 = c("q", "x", "f"), col_3 = c(1, 5, 3), col_4 = c("a", "v", "h"), stringsAsFactors = FALSE) # Add nodes from columns `col_1` and `col_2` # from the data frame to the graph object graph <- graph %>% add_nodes_from_df_cols( df = df, columns = c("col_1", "col_2")) # Show the graph's node data frame graph %>% get_node_df() #> id type label #> 1 1 <NA> 1 #> 2 2 <NA> 2 #> 3 3 <NA> f #> 4 4 <NA> p #> 5 5 <NA> q #> 6 6 <NA> x # Add new nodes from columns 3 and 4; # We can specify the columns by their # numbers as well graph <- graph %>% add_nodes_from_df_cols( df = df, columns = 3:4) # Show the graph's node data frame; note # that a node didn't get made with # `label == "1"` since that was already # in the graph (this behavior can be # changed with `keep_duplicates = TRUE`) graph %>% get_node_df() #> id type label #> 1 1 <NA> 1 #> 2 2 <NA> 2 #> 3 3 <NA> f #> 4 4 <NA> p #> 5 5 <NA> q #> 6 6 <NA> x #> 7 7 <NA> 5 #> 8 8 <NA> 3 #> 9 9 <NA> a #> 10 10 <NA> v #> 11 11 <NA> h