Skip to content

Instantly share code, notes, and snippets.

@trinker
Created November 26, 2017 05:09
Show Gist options
  • Select an option

  • Save trinker/eb71b7318732beddb36e782de8eb67f5 to your computer and use it in GitHub Desktop.

Select an option

Save trinker/eb71b7318732beddb36e782de8eb67f5 to your computer and use it in GitHub Desktop.
Tree Traverse
if (!require("pacman")) install.packages("pacman")
pacman::p_load(data.tree, tidyverse)
dat <- data_frame(
OrgUnitIdentifier = c(1, 6, 72, 147, 1471, 1553, 1771, 283, 3762, 1112, 31, 4353, 9374, 2612),
Name = c(
'Main University', 'Academic Affairs', 'College of Arts & Science', 'Biology', 'Biochemistry & Molecular Bio',
'Earth Sciences', 'Environmental Studies', 'Chemistry/Physics', 'Chemistry', 'Physics', 'College of Health Sciences',
'Health Sciences', 'Occupational Therapy', 'Social Work'
),
ParentIdentifier = c(NA, 1, 6, 72, rep(147, 3), 72, rep(283, 2), 6, rep(31, 3))
)
## OrgUnitIdentifier Name ParentIdentifier
## <dbl> <chr> <dbl>
## 1 1 Main University NA
## 2 6 Academic Affairs 1
## 3 72 College of Arts & Science 6
## 4 147 Biology 72
## 5 1471 Biochemistry & Molecular Bio 147
## 6 1553 Earth Sciences 147
## 7 1771 Environmental Studies 147
## 8 283 Chemistry/Physics 72
## 9 3762 Chemistry 283
## 10 1112 Physics 283
## 11 31 College of Health Sciences 6
## 12 4353 Health Sciences 31
## 13 9374 Occupational Therapy 31
## 14 2612 Social Work 31
## Handling the NA/NULL/Missing for root
key <- dat %>%
dplyr::select(OrgUnitIdentifier, Name) %>%
stats::setNames(c('id', 'name'))
key2 <- dat %>%
dplyr::select(OrgUnitIdentifier, ParentIdentifier)
## iterate up the tree
struct <- apply(key2, 1, function(x){
if (is.na(x[['ParentIdentifier']])) return(x[['OrgUnitIdentifier']])
par <- x[['ParentIdentifier']]
path <- unlist(x)
i <- length(path) + 1
while(!is.na(par)){
path[i] <- key2[['ParentIdentifier']][match(par, key2[['OrgUnitIdentifier']])]
par <- path[i]
i <- i + 1
}
return(rev(c(stats::na.omit(unname(path)))))
})
tree <- struct %>%
textshape::tidy_list('org', 'path') %>%
dplyr::left_join(key, by = c('path' = 'id')) %>%
dplyr::group_by(org) %>%
dplyr::summarize(pathString = paste(unlist(name), collapse = '<>')) %>%
data.tree::as.Node(pathDelimiter = '<>')
ptree <- gsub("\\G\\d", ' ', capture.output(tree), perl = TRUE)[-1]
rep <- paste('^', gsub('(^\\s+)(\\s\\S.+$)', '\\1', ptree[1]))
cat(paste(gsub(rep, '', ptree), collapse = '\n'), '\n')
## Main University
## °--Academic Affairs
## ¦--College of Arts & Science
## ¦ ¦--Chemistry/Physics
## ¦ ¦ ¦--Physics
## ¦ ¦ °--Chemistry
## ¦ °--Biology
## ¦ ¦--Biochemistry & Molecular Bio
## ¦ ¦--Earth Sciences
## ¦ °--Environmental Studies
## °--College of Health Sciences
## ¦--Health Sciences
## ¦--Occupational Therapy
## °--Social Work
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment