Last active
August 29, 2015 14:24
-
-
Save gluc/877f2373817465ab0c5b to your computer and use it in GitHub Desktop.
Convert igraph-style taxonomy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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