Skip to content

Commit

Permalink
calculate height for ape/phylo
Browse files Browse the repository at this point in the history
  • Loading branch information
cjyetman committed Jun 18, 2017
1 parent f9c30ba commit 2953369
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions R/as.treenetdf.R
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,27 @@ as.treenetdf.phylo <- function(data = NULL, ...) {
df <- data.frame(nodeId = data$edge[, 2],
parentId = data$edge[, 1],
name = data$tip.label[data$edge[, 2]],
depth = data$edge.length,
edge.length = data$edge.length,
depth = NA,
stringsAsFactors = F)

rootId <- unique(df$parentId[! df$parentId %in% df$nodeId])
df <- rbind(c(nodeId = rootId, parentId = NA, name = NA, depth = 1), df)

calc_height <- function(parentId) {
childIdxs <- df$parentId == parentId
childIds <- df$nodeId[childIdxs]

parentHeight <- df$depth[df$nodeId == parentId]
if (length(parentHeight) == 0) { parentHeight <- 0 }
df$depth[childIdxs] <<- df$edge.length[childIdxs] + parentHeight

if (length(childIds) > 0) { lapply(childIds, calc_height) }
invisible(df)
}
df <- calc_height(rootId)

df$height <- max(df$depth) - df$depth
df <- rbind(c(nodeId = rootId, parentId = NA, name = NA, edge.length = 0, depth = 0, height = max(df$depth)), df)

if (require('tibble')) { return(tibble::as.tibble(df)) }
return(df)
Expand Down

0 comments on commit 2953369

Please sign in to comment.