]> git.donarmstrong.com Git - ape.git/blob - R/mantel.test.R
some updates (including new CADM.global.Rd file)
[ape.git] / R / mantel.test.R
1 ## mantel.test.R (2011-06-22)
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                          alternative = "two.sided", ...)
28 {
29     alternative <- match.arg(alternative, c("two.sided", "less", "greater"))
30     n <- nrow(m1)
31     realz <- mant.zstat(m1, m2)
32     nullstats <- replicate(nperm, mant.zstat(m1, perm.rowscols(m2, n)))
33     pval <- switch(alternative,
34                    "two.sided" = 2 * sum(abs(nullstats) > abs(realz)),
35                    "less" = sum(nullstats < realz),
36                    "greater" = sum(nullstats > realz))
37     pval <- pval / nperm
38     if (graph) {
39         plot(density(nullstats), type = "l", ...)
40         abline(v = realz)
41     }
42     list(z.stat = realz, p = pval, alternative = alternative)
43 }