Skip to content

Instantly share code, notes, and snippets.

@gluc
Last active August 29, 2015 14:24
Show Gist options
  • Save gluc/877f2373817465ab0c5b to your computer and use it in GitHub Desktop.
Save gluc/877f2373817465ab0c5b to your computer and use it in GitHub Desktop.
Convert igraph-style taxonomy
library(data.tree)
library(igraph)
taxonomy <- data.frame(
children = LETTERS[2:13],
parents = c("A", "A", "B", "B", "C", "C", "C", "E", "E", "G", "H",
"H"),
child.level = c(2, 2, 3, 3, 3, 3, 3,4, 4, 4, 4, 4),
description = c("w", "i", "z", "v", "j", "u", "q", "g", "b", "c", "t",
"o"),
stringsAsFactors = FALSE
)
# 1. How to convert
#
# Note 1: This works on the current master from github
# devtools::install_github("gluc/data.tree")
# This will be released to CRAN some time in August
#
# Note 2: I'm currently working on a direct conversion from
# and to igraph. But that's not available yet.
root <- unique(taxonomy$parents[!(taxonomy$parents %in% taxonomy$children)])
g <- igraph::graph.data.frame(taxonomy[,1:2], directed = FALSE)
GetPath <- function(child) {
paste(names(all_simple_paths(g, from = root, child)[[1]]), collapse = "/")
}
taxonomy$pathString <- sapply(taxonomy$children, GetPath)
taxtree <- as.Node(taxonomy[, -c(1, 2, 3)]
print(taxtree, "description", "level")
#2. Get ancestors
m <- taxtree$Find("C", "H", "M")
m$path
m$parent$Get("name", traversal = "ancestor")
#3. Get description
m$Get("description", traversal = "ancestor")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment