]> git.donarmstrong.com Git - ape.git/blob - R/balance.R
new option 'rotate.tree' in plot.phylo()
[ape.git] / R / balance.R
1 ## balance.R (2009-05-10)
2
3 ##   Balance of a Dichotomous Phylogenetic Tree
4
5 ## Copyright 2002-2009 Emmanuel Paradis
6
7 ## This file is part of the R-package `ape'.
8 ## See the file ../COPYING for licensing issues.
9
10 balance <- function(phy)
11 {
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)
16     nb.node <- phy$Nnode
17     if (nb.node != N - 1)
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)
27     }
28     foo(N + 1, N)
29     rownames(ans) <-
30       if (is.null(phy$node.label)) N + 1:nb.node else phy$node.label
31     ans
32 }