1 ## vcv.phylo.R (2012-02-21)
3 ## Phylogenetic Variance-Covariance or Correlation Matrix
5 ## Copyright 2002-2012 Emmanuel Paradis
7 ## This file is part of the R-package `ape'.
8 ## See the file ../COPYING for licensing issues.
10 vcv <- function(phy, ...) UseMethod("vcv")
12 vcv.phylo <- function(phy, model = "Brownian", corr = FALSE, ...)
14 if (is.null(phy$edge.length))
15 stop("the tree has no branch lengths")
19 phy <- reorder(phy, "pruningwise")
21 n <- length(phy$tip.label)
26 ## xx: vecteur donnant la distance d'un noeud
27 ## ou d'un tip à partir de la racine
28 ## (same than in is.ultrametric)
29 xx <- numeric(n + phy$Nnode)
31 vcv <- matrix(0, n, n)
33 ## the loop below starts from the bottom of the edge matrix, so
36 for (i in length(e1):1) {
37 var.cur.node <- xx[e1[i]]
38 xx[e2[i]] <- var.cur.node + EL[i] # sets the variance
40 while (e1[j] == e1[i] && j > 0) {
41 left <- if (e2[j] > n) pp[[e2[j] - n]] else e2[j]
42 right <- if (e2[i] > n) pp[[e2[i] - n]] else e2[i]
43 vcv[left, right] <- vcv[right, left] <- var.cur.node # sets the covariance
48 diag.elts <- 1 + 0:(n - 1)*(n + 1)
49 vcv[diag.elts] <- xx[1:n]
52 ## This is inspired from the code of cov2cor (2005-09-08):
53 Is <- sqrt(1 / vcv[diag.elts])
54 ## below 'vcv[] <- ...' has been changed to 'vcv <- ...'
55 ## which seems to be twice faster for n = 1000 and
56 ## respects the additional attributes (2012-02-21):
57 vcv <- Is * vcv * rep(Is, each = n)
61 dimnames(vcv)[1:2] <- list(phy$tip.label)
65 vcv.corPhyl <- function(phy, corr = FALSE, ...)
67 labels <- attr(phy, "tree")$tip.label
68 dummy.df <- data.frame(1:length(labels), row.names = labels)
69 res <- nlme::corMatrix(Initialize.corPhyl(phy, dummy.df), corr = corr)
70 dimnames(res) <- list(labels, labels)