]> git.donarmstrong.com Git - ape.git/blob - R/mantel.test.R
new image.DNAbin()
[ape.git] / R / mantel.test.R
1 ## mantel.test.R (2006-07-28)
2
3 ##   Mantel Test for Similarity of Two Matrices
4
5 ## Copyright 2002-2006 Ben Bolker and Julien Claude
6
7 ## This file is part of the R-package `ape'.
8 ## See the file ../COPYING for licensing issues.
9
10 perm.rowscols <- function(m1, n)
11 {
12     s <- sample(1:n)
13     m1[s, s]
14 }
15
16 ### calculate the Mantel z-statistic for two square matrices m1 and m2
17 mant.zstat <- function(m1, m2) sum(lower.triang(m1 * m2))
18
19 lower.triang <- function(m)
20 {
21     d <- dim(m)
22     if (d[1] != d[2]) print("Warning: non-square matrix")
23     m[col(m) <= row(m)]
24 }
25
26 mantel.test <- function (m1, m2, nperm = 1000, graph = FALSE, ...)
27 {
28     n <- nrow(m1)
29     realz <- mant.zstat(m1, m2)
30     nullstats <- replicate(nperm, mant.zstat(m1, perm.rowscols(m2, n)))
31     pval <- sum(nullstats > realz)/nperm
32     if (graph) {
33         plot(density(nullstats), type = "l", ...)
34         abline(v = realz)
35     }
36     list(z.stat = realz, p = pval)
37 }