]> git.donarmstrong.com Git - ape.git/blob - R/dist.gene.R
new operators for "multiPhylo" + fixed small bug in bind.tree()
[ape.git] / R / dist.gene.R
1 ## dist.gene.R (2009-04-01)
2
3 ##   Pairwise Distances from Genetic Data
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 dist.gene <-
11     function(x, method = "pairwise", pairwise.deletion = FALSE,
12              variance = FALSE)
13 {
14     if (!is.data.frame(x) && !is.matrix(x))
15         stop("'x' should be a matrix or a data.frame")
16     method <- match.arg(method, c("pairwise", "percentage"))
17
18     if (!pairwise.deletion) {
19         ## delete the columns with at least one NA:
20         del <- apply(x, 2, function(xx) any(is.na(xx)))
21         x <- x[, !del]
22     }
23     n <- dim(x)
24     L <- n[2]
25     n <- n[1]
26     D <- double(n*(n - 1)/2)
27     if (pairwise.deletion) L <- D
28     k <- 1
29     for (i in 1:(n - 1)) {
30         for (j in (i + 1):n) {
31             y <- x[i, ] != x[j, ]
32             if (pairwise.deletion) L[k] <- sum(!is.na(y))
33             D[k] <-  sum(y, na.rm = TRUE)
34             k <- k + 1
35         }
36     }
37     ## L is either a single integer value if pairwise.deletion = FALSE,
38     ## or a vector of integers if pairwise.deletion = TRUE
39
40     if (method == "percentage") D <- D/L
41
42     attr(D, "Size") <- n
43     attr(D, "Labels") <-  dimnames(x)[[1]]
44     attr(D, "Diag") <- attr(D, "Upper") <- FALSE
45     attr(D, "call") <- match.call()
46     attr(D, "method") <- method
47     class(D) <- "dist"
48
49     if (variance) {
50         y <- if (method == "pairwise") L else 1
51         attr(D, "variance") <- D*(y - D)/L
52     }
53     D
54 }