Advertisement
Guest User

Untitled

a guest
Aug 2nd, 2015
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. library(data.tree)
  2. library(igraph)
  3. taxonomy <- data.frame(
  4. children = LETTERS[2:13],
  5. parents = c("A", "A", "B", "B", "C", "C", "C", "E", "E", "G", "H",
  6. "H"),
  7. child.level = c(2, 2, 3, 3, 3, 3, 3,4, 4, 4, 4, 4),
  8. description = c("w", "i", "z", "v", "j", "u", "q", "g", "b", "c", "t",
  9. "o"),
  10. stringsAsFactors = FALSE
  11. )
  12.  
  13. # 1. How to convert
  14. #
  15. # Note 1: This works on the current master from github
  16. # devtools::install_github("gluc/data.tree")
  17. # This will be released to CRAN some time in August
  18. #
  19. # Note 2: I'm currently working on a direct conversion from
  20. # and to igraph. But that's not available yet.
  21.  
  22. root <- unique(taxonomy$parents[!(taxonomy$parents %in% taxonomy$children)])
  23. g <- igraph::graph.data.frame(taxonomy[,1:2], directed = FALSE)
  24.  
  25. GetPath <- function(child) {
  26. paste(names(all_simple_paths(g, from = root, child)[[1]]), collapse = "/")
  27. }
  28.  
  29. taxonomy$pathString <- sapply(taxonomy$children, GetPath)
  30.  
  31. taxtree <- as.Node(taxonomy[, -c(1, 2, 3)]
  32. print(taxtree, "description", "level")
  33.  
  34. #2. Get ancestors
  35.  
  36. m <- taxtree$Find("C", "H", "M")
  37. m$path
  38. m$parent$Get("name", traversal = "ancestor")
  39.  
  40. #3. Get description
  41. m$Get("description", traversal = "ancestor")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement