tree_rewrite | R Documentation |
Rewrite the tree with a list of replacements
tree_rewrite(root, replacements)
root |
The root tree, obtained via |
replacements |
A list of replacements, obtained via |
A string character corresponding to the code used to build the tree root but with replacements applied.
src <- "x <- c(1, 2, 3)
any(duplicated(x), na.rm = TRUE)
any(duplicated(x))
if (any(is.na(x))) {
TRUE
}
any(is.na(y))"
root <- tree_new(src) |>
tree_root()
### Only replace the first nodes found by each rule
nodes_to_replace <- root |>
node_find(
ast_rule(id = "any_na", pattern = "any(is.na($VAR))"),
ast_rule(id = "any_dup", pattern = "any(duplicated($VAR))")
)
fixes <- nodes_to_replace |>
node_replace(
any_na = "anyNA(~~VAR~~)",
any_dup = "anyDuplicated(~~VAR~~) > 0"
)
# original code
cat(src)
# new code
tree_rewrite(root, fixes)
### Replace all nodes found by each rule
nodes_to_replace <- root |>
node_find_all(
ast_rule(id = "any_na", pattern = "any(is.na($VAR))"),
ast_rule(id = "any_dup", pattern = "any(duplicated($VAR))")
)
fixes <- nodes_to_replace |>
node_replace_all(
any_na = "anyNA(~~VAR~~)",
any_dup = "anyDuplicated(~~VAR~~) > 0"
)
# original code
cat(src)
# new code
tree_rewrite(root, fixes)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.