I would like to create a flat data.frameof wood in R.
The tree is represented by a list in which each contains a key with a name childrenthat contains more lists with a large number of children.
tree <-
list(name="root",
parent_name='None',
children=list(
list(parent_name="root", name="child1", children=list()),
list(parent_name="root", name="child2", children=list(list(parent_name="child2", name="child3", children=c())))
)
)
I would like to โsmoothโ this in data.framewith the following structure:
name parent_name
1 root None
2 child1 root
3 child2 root
4 child3 child2
I can accomplish this using the following recursive function:
walk_tree <- function(node) {
results <<- rbind(
results,
data.frame(
name=node$name,
parent_name=node$parent_name,
stringsAsFactors=FALSE
)
)
for (node in node$children) {
walk_tree(node)
}
}
This function works fine, but requires me to declare results data.frameoutside the function:
results <- NULL
walk_tree(tree)
results
In addition, using an operator <<-triggers the following warning when a function is walk_treeincluded as a function in a package:
Note: no visible binding for '<<-' assignment to 'results'
The use of the operator is <-not performed ( resultsafter walk_tree) is evaluated NULL).
data.frame R?