
Last chance! 50% off unlimited learning
Sale ends in
Within a graph's internal node data frame (ndf), recode character or numeric node attribute values. Optionally, one can specify a replacement value for any unmatched mappings.
recode_node_attrs(graph, node_attr_from, ..., otherwise = NULL,
node_attr_to = NULL)
a graph object of class
dgr_graph
.
the name of the node attribute column from which values will be recoded.
single-length character vectors with
the recoding instructions. The first component should
have the value to replace and the second should have
the replacement value (in the form
"[to_replace] -> [replacement]", ...
).
an optional single value for recoding any unmatched values.
an optional name of a new node attribute to which the recoded values will be applied. This will retain the original node attribute and its values.
a graph object of class
dgr_graph
.
# NOT RUN {
# Create a random graph
graph <-
create_random_graph(
5, 10, set_seed = 3) %>%
set_node_attrs(
"shape",
c("circle", "hexagon", "rectangle",
"rectangle", "circle"))
# Get the graph's internal ndf to show which
# node attributes are available
get_node_df(graph)
#> id type label value shape
#> 1 1 <NA> 1 2.0 circle
#> 2 2 <NA> 2 8.5 hexagon
#> 3 3 <NA> 3 4.0 rectangle
#> 4 4 <NA> 4 3.5 rectangle
#> 5 5 <NA> 5 6.5 circle
# Recode the `shape` node attribute, so that
# `circle` is recoded to `square` and that
# `rectangle` becomes `triangle`
graph <-
graph %>%
recode_node_attrs(
"shape",
"circle -> square",
"rectangle -> triangle")
# Get the graph's internal ndf to show that the
# node attribute values had been recoded
get_node_df(graph)
#> id type label value shape
#> 1 1 <NA> 1 2.0 square
#> 2 2 <NA> 2 8.5 hexagon
#> 3 3 <NA> 3 4.0 triangle
#> 4 4 <NA> 4 3.5 triangle
#> 5 5 <NA> 5 6.5 square
# Create a new node attribute, called `color`,
# that is based on a recoding of `shape`; here,
# map the square shape to a `red` color and map
# all other shapes to a `green` color
graph <-
graph %>%
recode_node_attrs(
"shape",
"square -> red",
otherwise = "green",
node_attr_to = "color")
# Get the graph's internal ndf to see the change
get_node_df(graph)
#> id type label value shape color
#> 1 1 <NA> 1 2.0 square red
#> 2 2 <NA> 2 8.5 hexagon green
#> 3 3 <NA> 3 4.0 triangle green
#> 4 4 <NA> 4 3.5 triangle green
#> 5 5 <NA> 5 6.5 square red
# Numeric values can be recoded as well;
# here, perform several recodings for
# values of the `value` node attribute
graph <-
graph %>%
recode_node_attrs(
"value",
"2.0 -> 9.5",
"4.0 -> 10.5",
otherwise = 5.0)
# Look at the graph's internal ndf
get_node_df(graph)
#> id type label value shape color
#> 1 1 <NA> 1 9.5 square red
#> 2 2 <NA> 2 5.0 hexagon green
#> 3 3 <NA> 3 10.5 triangle green
#> 4 4 <NA> 4 5.0 triangle green
#> 5 5 <NA> 5 5.0 square red
# }
Run the code above in your browser using DataLab