1 ## balance.R (2009-05-10)
3 ## Balance of a Dichotomous Phylogenetic Tree
5 ## Copyright 2002-2009 Emmanuel Paradis
7 ## This file is part of the R-package `ape'.
8 ## See the file ../COPYING for licensing issues.
10 balance <- function(phy)
12 ### the tree must be in cladewise order
13 if (!inherits(phy, "phylo"))
14 stop('object "phy" is not of class "phylo"')
15 N <- length(phy$tip.label)
18 stop('"phy" is not rooted and fully dichotomous')
19 ans <- matrix(NA, nb.node, 2)
20 foo <- function(node, n) {
21 s <- which(phy$edge[, 1] == node)
22 desc <- phy$edge[s, 2]
23 ans[node - N, 1] <<- n1 <- (s[2] - s[1] + 1)/2
24 ans[node - N, 2] <<- n2 <- n - n1
25 if (desc[1] > N) foo(desc[1], n1)
26 if (desc[2] > N) foo(desc[2], n2)
30 if (is.null(phy$node.label)) N + 1:nb.node else phy$node.label