-
Notifications
You must be signed in to change notification settings - Fork 0
/
plotDistances.R
212 lines (201 loc) · 7.58 KB
/
plotDistances.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
plotDistances = function(p = GlobalPatterns, m = "wunifrac", s = "X.SampleID", d = "SampleType", plot = TRUE, dont_consider_abundance = F) {
require("phyloseq")
require("dplyr")
require("reshape2")
require("ggplot2")
require("rbiom")
# calc distances
if (m=="wunifrac"){wu = rbiom::unifrac(otu_table(p), weighted=TRUE, tree=phy_tree(p))}
if (m=="unifrac"){wu = rbiom::unifrac(otu_table(p), weighted=FALSE, tree=phy_tree(p))}
if (m!="wunifrac"&m!="unifrac") {wu = phyloseq::distance(p, m, binary = dont_consider_abundance)}
wu.m = melt(as.matrix(wu))
# remove self-comparisons
wu.m = wu.m %>%
filter(as.character(Var1) != as.character(Var2)) %>%
mutate_if(is.factor, as.character)
# get sample data (S4 error OK and expected)
sd = as(sample_data(p),"data.frame") %>%
dplyr::select(s, d) %>%
mutate_if(is.factor,as.character)
# combined distances with sample data
colnames(sd) = c("Var1", "Type1")
wu.sd = left_join(wu.m, sd, by = "Var1")
colnames(sd) = c("Var2", "Type2")
wu.sd = left_join(wu.sd, sd, by = "Var2")
# plot
p = ggplot(wu.sd, aes(x = Type2, y = value)) +
theme_bw() +
geom_point() +
geom_boxplot(aes(color = ifelse(Type1 == Type2, "red", "black"))) +
scale_color_identity() +
facet_wrap(~ Type1, scales = "free_x") +
theme(axis.text.x=element_text(angle = 90, hjust = 1, vjust = 0.5)) +
ggtitle(paste0("Distance Metric = ", m)) +
ylab(m) +
xlab(d)
# return
if (plot == TRUE) {
return(p)
} else {
return(wu.sd)
}
}
betadisper_P <- function(d, group, type = c("median","centroid"), bias.adjust=FALSE,
sqrt.dist = FALSE, add = FALSE){
## inline function for double centring. We used .C("dblcen", ...,
## PACKAGE = "stats") which does not dublicate its argument, but
## it was removed from R in r60360 | ripley | 2012-08-22 07:59:00
## UTC (Wed, 22 Aug 2012) "more conversion to .Call, clean up".
dblcen <- function(x, na.rm = TRUE) {
cnt <- colMeans(x, na.rm = na.rm)
x <- sweep(x, 2L, cnt, check.margin = FALSE)
cnt <- rowMeans(x, na.rm = na.rm)
sweep(x, 1L, cnt, check.margin = FALSE)
}
## inline function for spatial medians
spatialMed <- function(vectors, group, pos) {
axes <- seq_len(NCOL(vectors))
spMedPos <- ordimedian(vectors, group, choices = axes[pos])
spMedNeg <- ordimedian(vectors, group, choices = axes[!pos])
cbind(spMedPos, spMedNeg)
}
## inline function for centroids
centroidFUN <- function(vec, group) {
cent <- apply(vec, 2,
function(x, group) tapply(x, INDEX = group, FUN = mean),
group = group)
if(!is.matrix(cent)) { ## if only 1 group, cent is vector
cent <- matrix(cent, nrow = 1,
dimnames = list(as.character(levels(group)),
paste0("Dim", seq_len(NCOL(vec)))))
}
cent
}
## inline function for distance computation
Resids <- function(x, c) {
if(is.matrix(c))
d <- x - c
else
d <- sweep(x, 2, c)
rowSums(d^2)
}
## Tolerance for zero Eigenvalues
TOL <- sqrt(.Machine$double.eps)
## uses code from stats:::cmdscale by R Core Development Team
if(!inherits(d, "dist"))
stop("distances 'd' must be a 'dist' object")
## Someone really tried to analyse correlation like object in range -1..+1
if (any(d < -TOL, na.rm = TRUE))
stop("dissimilarities 'd' must be non-negative")
## adjust to avoid negative eigenvalues (if they disturb you)
if (sqrt.dist)
d <- sqrt(d)
if (is.logical(add) && isTRUE(add))
add <- "lingoes"
if (is.character(add)) {
add <- match.arg(add, c("lingoes", "cailliez"))
if (add == "lingoes") {
ac <- addLingoes(as.matrix(d))
d <- sqrt(d^2 + 2 * ac)
}
else if (add == "cailliez") {
ac <- addCailliez(as.matrix(d))
d <- d + ac
}
}
if(missing(type))
type <- "median"
type <- match.arg(type)
## checks for groups - need to be a factor for later
group <- if(!is.factor(group)) {
as.factor(group)
} else { ## if already a factor, drop empty levels
droplevels(group, exclude = NA) # need exclude = NA under Rdevel r71113
}
n <- attr(d, "Size")
x <- matrix(0, ncol = n, nrow = n)
x[row(x) > col(x)] <- d^2
## site labels
labs <- attr(d, "Labels")
## remove NAs in group
if(any(gr.na <- is.na(group))) {
group <- group[!gr.na]
x <- x[!gr.na, !gr.na]
## update n otherwise C call crashes
n <- n - sum(gr.na)
## update labels
labs <- labs[!gr.na]
message("missing observations due to 'group' removed")
}
## remove NA's in d
if(any(x.na <- apply(x, 1, function(x) any(is.na(x))))) {
x <- x[!x.na, !x.na]
group <- group[!x.na]
## update n otherwise C call crashes
n <- n - sum(x.na)
## update labels
labs <- labs[!x.na]
message("missing observations due to 'd' removed")
}
x <- x + t(x)
x <- dblcen(x)
e <- eigen(-x/2, symmetric = TRUE)
vectors <- e$vectors
eig <- e$values
## Remove zero eigenvalues
eig <- eig[(want <- abs(eig) > max(TOL, TOL * eig[1L]))]
## scale Eigenvectors
vectors <- vectors[, want, drop = FALSE] %*% diag(sqrt(abs(eig)),
nrow = length(eig))
## store which are the positive eigenvalues
pos <- eig > 0
## group centroids in PCoA space
centroids <-
switch(type,
centroid = centroidFUN(vectors, group),
median = spatialMed(vectors, group, pos)
)
## for each of the groups, calculate distance to centroid for
## observation in the group
## Uses in-line Resids function as we want LAD residuals for
## median method, and LSQ residuals for centroid method
dist.pos <- Resids(vectors[, pos, drop=FALSE],
centroids[group, pos, drop=FALSE][1,]) ###############HERE IS THE THING
dist.neg <- 0
if(any(!pos))
dist.neg <- Resids(vectors[, !pos, drop=FALSE],
centroids[group, pos, drop=FALSE][1,]) ###############HERE IS THE THING
## zij are the distances of each point to its group centroid
if (any(dist.neg > dist.pos)) {
## Negative squared distances give complex valued distances:
## take only the real part (which is zero). Github issue #306.
warning("some squared distances are negative and changed to zero")
zij <- Re(sqrt(as.complex(dist.pos - dist.neg)))
} else {
zij <- sqrt(dist.pos - dist.neg)
}
if (bias.adjust) {
n.group <- as.vector(table(group))
zij <- zij*sqrt(n.group[group]/(n.group[group]-1))
}
## pre-compute group mean distance to centroid/median for `print` method
grp.zij <- tapply(zij, group, "mean")
## add in correct labels
if (any(want))
colnames(vectors) <- names(eig) <-
paste("PCoA", seq_along(eig), sep = "")
if(is.matrix(centroids))
colnames(centroids) <- names(eig)
else
names(centroids) <- names(eig)
rownames(vectors) <- names(zij) <- labs
retval <- list(eig = eig, vectors = vectors, distances = zij,
group = group, centroids = centroids,
group.distances = grp.zij, call = match.call())
class(retval) <- "betadisper"
attr(retval, "method") <- attr(d, "method")
attr(retval, "type") <- type
attr(retval, "bias.adjust") <- bias.adjust
retval
}
test<-betadisper_P(ord_mo_phase,as(sample_data(physeq_SRS_tmo_mo), "data.frame")$time, type="centroid")