-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRock_weathering_analysis4paper.RMD
1733 lines (1543 loc) · 64.7 KB
/
Rock_weathering_analysis4paper.RMD
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Role of BRC in arid rock weathering"
subtitle: "Data analysis and plotting for publication"
author: "Roey Angel (<[email protected]>)"
date: "`r Sys.Date()`"
bibliography: references.bib
link-citations: yes
always_allow_html: yes
output:
rmarkdown::html_document:
toc: true
toc_float: true
keep_md: true
keep_tex: true
number_sections: false
highlight: "pygments"
theme: "flatly"
dev: "png"
df_print: "kable"
fig_caption: true
code_folding: "show"
---
```{r libraries, include=F}
# Load libraries
#.libPaths(c('~/R/library', .libPaths())) # Uncomment if you have no write access to R path
repo <- "http://cran.wu.ac.at"
.cran_libs <- c(
"devtools", # Tools to Make Developing R Packages Easier
"knitr", # A General-Purpose Package for Dynamic Report Generation in R
"kableExtra", # Construct Complex Table with 'kable' and Pipe Syntax
"rmarkdown", # Dynamic Documents for R
"extrafont", # for extra figure fonts
"MASS", # Support Functions and Datasets for Venables and Ripley's MASS
"rcompanion", #Functions to Support Extension Education Program Evaluation
"tidyverse", # for dplyr forcats ggplot2 readr tibble
"cowplot", # wrappers for ggplot
"magrittr", # pipes
"scales", # Generic plot scaling methods
"svglite", # for svg files
"car", # Companion to Applied Regression
"userfriendlyscience", # Quantitative Analysis Made Accessible
"agricolae", # Statistical Procedures for Agricultural Research
"vegan", # community ecology methods
"doParallel", # parallel backend for the foreach/%dopar% function
"BiodiversityR", # Package for Community Ecology and Suitability Analysis
"hexbin", # Hexagonal Binning Routines
"ggtern", # An Extension to 'ggplot2', for the Creation of Ternary Diagrams
"nlme", # Linear and Nonlinear Mixed Effects Models
"MuMIn" # Multi-Model Inference
)
# .inst <- .cran_libs %in% installed.packages()
# if (any(!.inst)) {
# install.packages(.cran_libs[!.inst],
# repos = repo)
# }
.bioc_libs <- c(
"phyloseq", # Handling and analysis of high-throughput phylogenetic sequence data
"ALDEx2", # Analysis Of Differential Abundance Taking Sample Variation Into Account
"vsn" # Variance stabilization and calibration for microarray data
)
# if (!"phyloseq" %in% installed.packages()) {
# source(
# "https://raw.githubusercontent.com/joey711/phyloseq/master/inst/scripts/installer.R",
# local = TRUE
# )
# }
# .inst <- .bioc_libs %in% installed.packages()
# if (any(!.inst)) {
# source("http://bioconductor.org/biocLite.R")
# biocLite(ask = F, lib = Sys.getenv("R_LIBS_USER")) # upgrade bioC packages
# biocLite(.bioc_libs[!.inst], ask = F)
# }
.github_libs <- c(
"gadenbuie/ggpomological", # Pomological plot themes for ggplot2
"datarootsio/artyfarty" # Themes for ggplot2
)
.github_lib_names <- stringr::str_replace(.github_libs, ".*/(.*)$", "\\1")
# .github_inst <- .github_lib_names %in% installed.packages()
# if (any(!.github_inst)) {
# devtools::install_github(.github_libs[!.github_inst],
# dependencies = TRUE)
# }
# Load packages into session, and print package version
(loaded.libs <- sapply(c(.cran_libs, .bioc_libs, .github_lib_names), require, character.only = TRUE))
if (!all(loaded.libs)) {stop(paste("Package(s):", names(loaded.libs[loaded.libs == FALSE]), "could not be loaded"))}
# sapply(c(.cran_libs, .bioc_libs, .github_lib_names), packageVersion)
```
```{r style settings, include=F}
graphic_device <- "svglite"
options(width = 90, knitr.table.format = "html")
opts_chunk$set(
warning = FALSE,
message = FALSE,
cache = TRUE,
dev = graphic_device,
fig.ext = "svg",
# fig.width=12,
# fig.height=8,
cache.path = "Rock_weathering_cache/",
fig.path = "Rock_weathering_figures/"
)
f_name <- "DejaVu Sans" #sub("\\s//", "", f_name)
f_size <- 12
font_import(pattern = "DejaVuSans", prompt = FALSE)
loadfonts() # registers fonts
theme_set(theme_bw(base_size = f_size, base_family = f_name))
pom4 <- ggpomological:::pomological_palette[c(2, 1, 9, 3)]
pom2 <- c(ggpomological:::pomological_base[[7]], ggpomological:::pomological_palette[[1]])
```
```{r functions, include=F}
PlotLibDist <- function(physeq) {
ggplot(sample_data(physeq),
aes(x = Replicate, y = Lib.size, fill = Source)) +
geom_bar(stat = "identity",
position = "dodge",
color = "black") +
scale_y_log10(
breaks = trans_breaks("log10", function(x)
10 ^ x),
labels = trans_format("log10", math_format(10 ^ .x))
) +
background_grid(major = "xy", minor = "none") +
# scale_fill_locuszoom() +
facet_grid(Climate ~ .)
}
PlotReadHist <- function(OTUmat, b.width = 10) {
OTUmat %>%
t() %>%
as.tibble() %>%
gather(key = sample, value = abundance) %>%
ggplot(aes(abundance)) +
# geom_histogram(binwidth = 1000) +
geom_freqpoly(binwidth = b.width) +
scale_y_log10()
}
GMPR <- function(comm,
intersect.no = 4,
ct.min = 4) {
require(matrixStats)
# Taken from: https://github.com/jchen1981/GMPR
#
# Computes the GMPR size factor
#
# Args:
# comm: a matrix of counts, row - features (OTUs, genes, etc) , column - sample
# intersect.no: the minimum number of shared features between sample pair, where the ratio is calculated
# ct.min: the minimum number of counts required to calculate ratios (Empirical study found ct.min=4 is suitable)
#
# Returns:
# a list that contains:
# gmpr: the GMPR size factors for all samples; Samples with distinct sets of features will be output as NA.
# nss: number of samples with significant sharing (> intersect.no) including itself
# mask counts < ct.min
comm[comm < ct.min] <- 0
if (is.null(colnames(comm))) {
colnames(comm) <- paste0('S', 1:ncol(comm))
}
cat('Begin GMPR size factor calculation ...\n')
comm.no <- numeric(ncol(comm))
gmpr <- sapply(1:ncol(comm), function(i) {
if (i %% 50 == 0) {
cat(i, '\n')
}
x <- comm[, i]
# Compute the pairwise ratio
pr <- x / comm
# Handling of the NA, NaN, Inf
pr[is.nan(pr) | !is.finite(pr) | pr == 0] <- NA
# Counting the number of non-NA, NaN, Inf
incl.no <- colSums(!is.na(pr))
# Calculate the median of PR
pr.median <- colMedians(pr, na.rm = TRUE)
# Record the number of samples used for calculating the GMPR
comm.no[i] <<- sum(incl.no >= intersect.no)
# Geometric mean of PR median
if (comm.no[i] > 1) {
return(exp(mean(log(pr.median[incl.no >= intersect.no]))))
} else {
return(NA)
}
})
if (sum(is.na(gmpr))) {
warning(
paste0(
'The following samples\n ',
paste(colnames(comm)[is.na(gmpr)], collapse = '\n'),
'\ndo not share at least ',
intersect.no,
' common taxa with the rest samples! ',
'For these samples, their size factors are set to be NA! \n',
'You may consider removing these samples since they are potentially outliers or negative controls!\n',
'You may also consider decreasing the minimum number of intersecting taxa and rerun the procedure!\n'
)
)
}
cat('Completed!\n')
cat(
'Please watch for the samples with limited sharing with other samples based on NSS! They may be outliers! \n'
)
names(gmpr) <- names(comm.no) <- colnames(comm)
return(list(gmpr = gmpr, nss = comm.no))
}
PlotLmResid <- function(lm.df, which = c(1:6), mfrow = c(3, 2)){
require(grid)
if (length(levels(as.factor(lm.df$.fitted))) < 10) {# if number of unique x values is <10 just draw a line through the means
smoother <- stat_summary(fun.y = mean, colour = "red", geom = "line")
} else smoother <- stat_smooth(method = "loess", geom = "smooth", se = FALSE, colour = "firebrick", size = 1)
# residuals vs fitted
g1 <- ggplot(lm.df, aes(.fitted, .resid)) +
geom_point() +
smoother +
geom_hline(yintercept = 0, linetype = 2, size = .2) +
scale_x_continuous("Fitted Values") +
scale_y_continuous("Residual") +
labs(title = "Residuals vs Fitted")
# normal qq
a <- quantile(lm.df$.stdresid, c(0.25, 0.75), na.rm = TRUE)
b <- qnorm(c(0.25, 0.75))
slope <- diff(a)/diff(b)
int <- a[1] - slope * b[1]
g2 <- ggplot(lm.df, aes(sample = .stdresid)) +
stat_qq() +
geom_abline(slope = slope, intercept = int, colour = "firebrick", size = 1) +
scale_x_continuous("Theoretical Quantiles") +
scale_y_continuous("Standardized Quantiles") +
labs(title = "Normal Q-Q")
# scale-location
g3 <- ggplot(lm.df, aes(.fitted, sqrt(abs(.stdresid)))) +
geom_point() +
smoother +
scale_x_continuous("Fitted Values") +
scale_y_continuous("Root of Standardized Residuals") +
labs(title = "Scale-Location")
# residuals vs leverage
g4 <- ggplot(lm.df, aes(factors, .stdresid)) +
geom_point() +
smoother +
geom_hline(yintercept = 0, linetype = 2, size = .2) +
scale_x_continuous("Factor Level Combinations") +
scale_y_continuous("Standardized Residuals") +
labs(title = "Residuals vs Factor Levels")
# # cook's distance
# g5 <- ggplot(lm.df, aes(rows, .cooksd, ymin=0, ymax=.cooksd)) +
# geom_point() + geom_linerange() +
# scale_x_continuous("Observation Number") +
# scale_y_continuous("Cook's distance") +
# labs(title="Cook's Distance")
# cooksd vs leverage
g5 <- ggplot(lm.df, aes(factors, .cooksd)) +
geom_point() +
smoother +
scale_x_continuous("Factor Level Combinations") +
scale_y_continuous("Cook's distance") +
labs(title = "Cook's dist vs Leverage")
# g6 <- PlotACF(lm.df)
bw <- diff(range(lm.df$.resid)) / (2 * IQR(lm.df$.resid) / length(lm.df$.resid) ^ (1/3))
sshist <- function(x){ # optimise bins
# 2006 Author Hideaki Shimazaki
# Department of Physics, Kyoto University
# shimazaki at ton.scphys.kyoto-u.ac.jp
N <- 2 : 100
C <- numeric(length(N))
D <- C
for (i in 1:length(N)) {
D[i] <- diff(range(x)) / N[i]
edges = seq(min(x), max(x), length=N[i])
hp <- hist(x, breaks = edges, plot=FALSE)
ki <- hp$counts
k <- mean(ki)
v <- sum((ki-k) ^ 2) / N[i]
C[i] <- (2 * k-v) / D[i] ^ 2 #Cost Function
}
idx <- which.min(C)
optD <- D[idx]
bins <- seq(min(x), max(x), length=N[idx])
# h = hist(x, breaks = bins)
# rug(x)
return(bins)
}
bins <- sshist(lm.df$.resid)
g6 <- ggplot(lm.df, aes(.resid)) +
geom_histogram(breaks = bins)
plots <- list(g1, g2, g3, g4, g5, g6)
# making the plots
grid.newpage()
if (prod(mfrow) > 1) {
mypos <- expand.grid(1:mfrow[1], 1:mfrow[2])
mypos <- mypos[with(mypos, order(Var1)), ]
pushViewport(viewport(layout = grid.layout(mfrow[1], mfrow[2])))
formatter <- function(.){}
} else {
mypos <- data.frame(matrix(1, length(which), 2))
pushViewport(viewport(layout = grid.layout(1, 1)))
formatter <- function(.) {
.dontcare <- readline("Hit <Return> to see next plot: ")
grid.newpage()
}
}
j <- 1
for (i in which) {
formatter()
print(plots[[i]], vp = viewport(layout.pos.row = mypos[j, ][1], layout.pos.col = mypos[j, ][2]))
j <- j + 1
}
}
PlotACF <- function(lm.df){
## generate ACF plot for lm and lme
# compute acf without plotting
acz <- acf(lm.df$.resid, plot = F)
# convert to data frame
acd <- data.frame(lag = acz$lag, acf = acz$acf)
# use data frame for ggplot
ggplot(acd, aes(lag, acf)) +
geom_bar(colour = "black", fill = "black", stat = "identity", position = "dodge", width = 0.01) +
geom_point(colour = "black") +
geom_hline(yintercept = c(0.05, -0.05), linetype = "dashed") +
geom_hline(yintercept = 0)
}
TestAlpha <-
function(data2test = Richness_Diversity_long,
response_name = "Estimate",
factor_names = c("Climate", "Uni.Source"),
boxcox.trans = FALSE) {
print(leveneTest(as.formula(paste(response_name, paste(factor_names[1], factor_names[2], sep = " * "), sep = " ~ ")), data2test)) # test for homogeneity
mod_data <-
aov(as.formula(
paste(response_name, paste(factor_names[1], factor_names[2], sep = " * "), sep = " ~ ")
), data2test)
if (boxcox.trans) { # employ boxcox transformation then recalculate model
print("Performing Box-Cox transformation of the data")
lambdas <- boxcox(as.formula(
paste(response_name, paste(factor_names[1], factor_names[2], sep = " * "), sep = " ~ ")
), data=data2test, lambda = seq(0, 1.0, 0.01))
print(range(lambdas$x[lambdas$y > max(lambdas$y) - qchisq(0.95,1)/2]))
print(l.max <- lambdas$x[which.max(lambdas$y)])
if (l.max == 0) l.max <- 1
data2test$Estimate.box <- (data2test$Estimate ^ l.max - 1)/l.max
mod_data <-
aov(as.formula(
paste("Estimate.box", paste(factor_names[1], factor_names[2], sep = " * "), sep = " ~ ")
), data2test)
}
print(mod_data)
mod_data_df <- fortify(mod_data)
factor.combinations <-
as.numeric(factor(
paste(mod_data_df[, factor_names[1]], mod_data_df[, factor_names[2]]),
levels = unique(as.character(paste(
mod_data_df[, factor_names[1]], mod_data_df[, factor_names[2]]
)))
)) # needed for "residuals vs leverage
mod_data_df <-
cbind(mod_data_df,
rows = 1:nrow(mod_data_df),
factors = factor.combinations)
PlotLmResid(mod_data_df)
print(summary(mod_data)) # display Type I ANOVA table
# drop1(mod_amp.2,~.,test="F") # type III SS and F Tests
print(model.tables(mod_data,"means"), digits = 3) # Show the means
return(mod_data)
}
PairwiseAdonis <- function(x, factors, sim.function = "vegdist", sim.method = "bray",
p.adjust.m = "BH", reduce = NULL)
{
# Taken from: https://github.com/pmartinezarbizu/pairwiseAdonis
co <- combn(unique(as.character(factors)), 2)
pairs <- c()
total.DF <- c()
F.Model <- c()
R2 <- c()
p.value <- c()
for (elem in 1:ncol(co)) {
if (sim.function == "daisy") {
x1 = daisy(x[factors %in% c(co[1, elem], co[2, elem]),
], metric = sim.method)
}
else {
x1 = vegdist(x[factors %in% c(co[1, elem], co[2,
elem]), ], method = sim.method)
}
ad <- adonis(x1 ~ factors[factors %in% c(co[1, elem],
co[2, elem])], permutations = 9999)
pairs <- c(pairs, paste(co[1, elem], "vs", co[2, elem]))
total.DF <- c(total.DF, ad$aov.tab["Total", 1])
F.Model <- c(F.Model, ad$aov.tab[1, 4])
R2 <- c(R2, ad$aov.tab[1, 5])
p.value <- c(p.value, ad$aov.tab[1, 6])
}
p.adjusted <- p.adjust(p.value, method = p.adjust.m)
sig = c(rep("", length(p.adjusted)))
sig[p.adjusted <= 0.05] <- "."
sig[p.adjusted <= 0.01] <- "*"
sig[p.adjusted <= 0.001] <- "**"
sig[p.adjusted <= 1e-04] <- "***"
pairw.res <- data.frame(pairs, total.DF, F.Model, R2, p.value,
p.adjusted, sig)
if (!is.null(reduce)) {
pairw.res <- subset(pairw.res, grepl(reduce, pairs))
pairw.res$p.adjusted <- p.adjust(pairw.res$p.value, method = p.adjust.m)
sig = c(rep("", length(pairw.res$p.adjusted)))
sig[pairw.res$p.adjusted <= 0.05] <- "."
sig[pairw.res$p.adjusted <= 0.01] <- "*"
sig[pairw.res$p.adjusted <= 0.001] <- "**"
sig[pairw.res$p.adjusted <= 1e-04] <- "***"
pairw.res <- data.frame(pairw.res[, 1:5], sig)
}
class(pairw.res) <- c("pwadonis", "data.frame")
return(pairw.res)
}
STAMPR <- function(physeq_obj, rank = "Phylum", sig_pairs, threshold = 0.005) {
# run a STAMP-like analysis: compare relative abundance differences using two-way analysis, then run a post-hoc test and correct for multiple comparisons
physeq_glom <- tax_glom(physeq_obj,
rank,
NArm = TRUE)
physeq_glom_rel <-
transform_sample_counts(physeq_glom, function(x)
x / sum(x))
# group dataframe by rank, calculate median rel. abundance and keep taxa above threshold
physeq_glom_rel %>%
psmelt %>%
group_by_(rank) %>%
summarise(median = median(Abundance)) %>%
filter(median >= threshold) %>%
pull(1) %>%
as.character() ->
Taxa2test
physeq_glom_rel_abund <- prune_taxa(tax_table(physeq_glom_rel)[, rank] %in% Taxa2test, physeq_glom_rel)
taxa_test_results <-
bind_cols(Phylum = tax_table(physeq_glom_rel_abund)[, rank],
as.data.frame(matrix(
NA,
nrow = ntaxa(physeq_glom_rel_abund),
ncol = length(sig_pairs) + 6 # sig_pairs is taken from pairwise adonis
)))
colnames(taxa_test_results) <-
c(
rank,
"Climate - P",
"Climate - Eta",
"Source - P",
"Source - Eta",
"ClimateXSource - P",
"ClimateXSource - Eta",
sig_pairs
)
taxa_test_stats <-
bind_cols(Phylum = tax_table(physeq_glom_rel_abund)[, rank],
as.data.frame(matrix(
NA,
nrow = ntaxa(physeq_glom_rel_abund),
ncol = (length(sig_pairs) * 5) # sig_pairs is taken from pairwise adonis
)))
colnames(taxa_test_stats) <-
c(rank, c(rbind(
t(str_split_fixed(sig_pairs, " vs ", n = 2)), matrix(rep(
c("Estimate diff.", "low CI", "high CI"), length(sig_pairs)
), ncol = length(sig_pairs))
))) # this is ugly but it works well, basically c() flattens a matrix
for (phy_id in seq(ntaxa(physeq_glom_rel_abund))) {
data2test <-
bind_cols(Abundance = otu_table(physeq_glom_rel_abund)[, phy_id] * 100,
as(sample_data(physeq_glom_rel_abund), "data.frame"))
# kruskal.test(Abundance ~ Climate.Source, data = data2test)
print(tax_table(physeq_glom_rel_abund)[phy_id, rank])
print(SRH_mod <-
scheirerRayHare(Abundance ~ Climate + Source, data = data2test))
taxa_test_results[phy_id, c(2, 4, 6)] <-
SRH_mod$p.value[1:3] # p values
taxa_test_results[phy_id, c(3, 5, 7)] <-
SRH_mod$`Sum Sq`[1:3] / sum(SRH_mod$`Sum Sq`) # Eta (effect size)
for (pair in seq(length(sig_pairs))) {
pair2test <- unlist(str_split(sig_pairs[pair], " vs "))
possibleError <- tryCatch(
wilcox_mod <-
wilcox.test(
Abundance ~ Climate.Source,
data = data2test,
subset = Climate.Source %in% pair2test,
conf.int = TRUE,
exact = FALSE
),
error = function(e) e
) # AKA Mann Whitney
if (inherits(possibleError, 'error')) {
print(possibleError)
taxa_test_results[phy_id, pair + 7] <- NA
} else {
print(wilcox_mod)
taxa_test_results[phy_id, pair + 7] <- wilcox_mod$p.value
taxa_test_stats[phy_id, (pair - 1) * 5 + 2] <-
mean(data2test[data2test$Climate.Source %in% pair2test[1],]$Abundance)
taxa_test_stats[phy_id, (pair - 1) * 5 + 3] <-
mean(data2test[data2test$Climate.Source %in% pair2test[2],]$Abundance)
taxa_test_stats[phy_id, (pair - 1) * 5 + 4] <-
wilcox_mod$estimate
taxa_test_stats[phy_id, (pair - 1) * 5 + c(5, 6)] <-
wilcox_mod$conf.int[c(1, 2)]
}
}
}
# Correct for FDR for each comparison pair
for (pair in seq(2, ncol(taxa_test_results))) {
# print(pair)
taxa_test_results[, pair] <-
p.adjust(pull(taxa_test_results[, pair]) , method = "BH") # Benjamini, Y., and Yekutieli, D. (2001). The control of the false discovery rate in multiple testing under dependency. Annals of Statistics 29, 1165–1188.
# qvalue(p = pull(taxa_test_results[, pair]))
}
write.csv(taxa_test_results, file = paste0("Results/", deparse(substitute(physeq_obj)), "_", rank, "_Pvals.csv"))
write.csv(taxa_test_stats, file = paste0("Results/", deparse(substitute(physeq_obj)), "_", rank, "_CI.csv"))
Taxa_tests <- list(taxa_test_results, taxa_test_stats)
return(Taxa_tests)
}
CalcALDEx <- function(physeq_obj = Rock_weathering_filt3_Rocks, sig_level = 0.05, LFC = 0.322) {
physeq_obj <- filter_taxa(physeq_obj, function(x) sum(x) > 0, TRUE)
# physeq_obj <- prune_taxa(sig_taxa, physeq_obj) # remove taxa not significant under the full model
data2test <- t(otu_table(physeq_obj))
comparison <- as.character(unlist(sample_data(physeq_obj)[, "Climate.Source"]))
ALDEx <- aldex.clr(
data2test,
comparison,
mc.samples = 128,
denom = "iqlr", # iqlr for slight assymetry in composition
verbose = TRUE,
useMC = TRUE
)
ALDEx_tt <- aldex.ttest(ALDEx, comparison, paired.test = FALSE) # for two conditions
ALDEx_effect <- aldex.effect(
ALDEx,
comparison,
include.sample.summary = TRUE,
verbose = TRUE,
useMC = TRUE
) # estimate effect sizes
ALDEx2plot <- PrepAlDExData(ALDEx_tt, ALDEx_effect, physeq_obj, sig_level, LFC, Taxa_rank)
return(ALDEx2plot)
}
PrepAlDExData <- function(ALDEx_tt, ALDEx_effect, physeq_obj = Rock_weathering_filt3_Rocks, sig_level, LFC, Taxa_rank) {
ALDEx2plot <- data.frame(ALDEx_tt, ALDEx_effect) # merge results
# group dataframe by OTU, calculate median rel. abundance
physeq_obj %>%
transform_sample_counts(., function(x) x / sum(x) * 100) %>%
psmelt() %>%
group_by(OTU) %>%
# filter(OTU %in% sig_taxa) %>%
summarise(baseMean = mean(Abundance)) ->
baseMean
ALDEx2plot$OTU <- rownames(ALDEx2plot)
ALDEx2plot %<>% left_join(., baseMean, by = "OTU") # add mean abundance to results table
ALDEx2plot$Phylum <-
tax_table(physeq_obj)[taxa_names(physeq_obj) %in% ALDEx2plot$OTU, "Phylum"] # add phylum data
# change their name to "Rare"
ALDEx2plot[ALDEx2plot$Phylum %in% Rare_phyla,]$Phylum <- 'Rare' # Rare_phyla is calcuted for the taxa box plots
ALDEx2plot$Significance <- factor("Fail", levels = c("Fail", "Pass")) # define significance factor
ALDEx2plot$Significance[ALDEx2plot$wi.eBH < sig_level &
!is.na(ALDEx2plot$wi.eBH) &
abs(ALDEx2plot$effect) > LFC] <- "Pass"
# ALDEx2plot$Significance <- as.factor(sapply(ALDEx2plot$wi.eBH, function(x) if (is.na(x) | x > 0.05) {x <- "Fail"} else {x <- "Pass"}))
# Rank by taxa abundance
ALDEx2plot$Phylum %<>%
factor(., levels = Taxa_rank$Phylum) %>% # Taxa_rank is calcuted for the taxa box plots
fct_relevel(., "Rare", after = Inf)
return(ALDEx2plot)
}
GGPlotALDExTax <- function(ALDEx2plot, OTU_labels = FALSE, Taxa = "Phylum", Y_val = "effect", sig_level = 0.05) {
p <-
ggplot(ALDEx2plot) +
geom_jitter(aes_string(
x = Taxa,
y = Y_val,
colour = "Significance",
size = "baseMean"),
alpha = 2 / 3,
width = 0.3,
stroke = 0) +
xlab("") +
ylab(expression(paste("Effect size (lo", g[2], " fold change)"))) +
# ylab("Fold change") +
labs(colour = paste("Significance at \n p <", sig_level), size = "Mean count (%)") +
theme_grey(base_size = 18, base_family = f_name) +
theme(axis.text.x = element_text(angle = 45.0, vjust = 1, hjust = 1)) +
guides(colour = guide_legend(override.aes = list(size = 5))) +
scale_colour_manual(values = pom2) +
scale_size_continuous(range = c(1, 5), breaks = c(1, 2.5, 5, 10))
if (OTU_labels) {
p <- p + geom_text_repel(
aes_string(x = Taxa, y = Y_val),
size = 8,
label = sub("OTU_([0-9]+)", "\\1", rownames(ALDEx2plot[ALDEx2plot$Significance == "Pass", ])),
data = ALDEx2plot[ALDEx2plot$Significance == "Pass", ],
nudge_x = 0.4,
colour = "#707070"
)
}
return(p)
}
gz <- function(in_path, out_path = tempfile()) {
# Compress a file using gz and delete the uncompressed file
out <- gzfile(out_path, "w")
writeLines(readLines(in_path), out)
close(out)
file.remove(in_path)
invisible(out_path)
}
```
## New insights into the role of epilithic biological crust in arid rock weathering
This script reproduces all sequence analysis steps and plots included in the paper plus some additional exploratory analyses.
The analysis is heavily based on the phyloseq package [@mcmurdie_phyloseq_2013], but also on many other R packages.
```{r general parameters}
set.seed(123456789)
bootstraps <- 1000
min_lib_size <- 1000
```
**Load data**
```{r load data, cache=T}
read.csv("Data/Rock_weathering_new2_otuTab.txt", header = TRUE, row.names = 1, sep = "\t") %>%
t() %>%
as.data.frame() ->
Rock_weathering_OTUmat
sort_order <- as.numeric(gsub("OTU([0-9]+)", "\\1", colnames(Rock_weathering_OTUmat)))
Rock_weathering_OTUmat <- Rock_weathering_OTUmat[, order(sort_order)]
row.names(Rock_weathering_OTUmat) <- gsub("(.*)Nimrod[0-9]+|Osnat[0-9]+", "\\1", row.names(Rock_weathering_OTUmat))
Metadata <- read.csv("Data/Rock_weathering_metadata_RA.csv", row.names = 1, header = TRUE)
# Order abundance_mat samples according to the metadata
sample_order <- match(row.names(Rock_weathering_OTUmat), row.names(Metadata))
Rock_weathering_OTUmat %<>% arrange(., sample_order)
Metadata$sample_names <- row.names(Metadata)
Metadata$Uni.Source <- fct_collapse(Metadata$Source, Rock = c("Dolomite", "Limestone"))
Metadata$Climate.Source <-
factor(
paste(
Metadata$Climate,
Metadata$Source
),
levels = c(
"Arid Limestone",
"Arid Dust",
"Arid Loess soil",
"Hyperarid Dolomite",
"Hyperarid Dust",
"Hyperarid Loess soil"
),
labels = c(
"Arid limestone",
"Arid dust",
"Arid loess soil",
"Hyperarid dolomite",
"Hyperarid dust",
"Hyperarid loess soil"
)
)
Metadata$Climate.UniSource <-
factor(
paste(
Metadata$Climate,
Metadata$Uni.Source
),
levels = c(
"Arid Rock",
"Arid Dust",
"Arid Loess soil",
"Hyperarid Rock",
"Hyperarid Dust",
"Hyperarid Loess soil"
),
labels = c(
"Arid rock",
"Arid dust",
"Arid loess soil",
"Hyperarid rock",
"Hyperarid dust",
"Hyperarid loess soil"
)
)
# calculate sample size
Metadata$Lib.size = rowSums(Rock_weathering_OTUmat)
row.names(Rock_weathering_OTUmat) <- row.names(Metadata)
# Load taxonomy data
tax.file <- "Data/Rock_weathering_new2_silva.nrv119.taxonomy"
Taxonomy <- read.table(tax.file, stringsAsFactors = FALSE) # read taxonomy file
# count how many ';' in each cell and add up to 6
for (i in 1:nrow(Taxonomy)) {
semicolons <- length(gregexpr(";", Taxonomy$V2[i])[[1]])
if (semicolons < 6) {
x <- paste0(rep("Unclassified;", 6 - semicolons), collapse = "")
Taxonomy$V2[i] <- paste0(Taxonomy$V2[i], x, sep = "")
}
}
do.call( "rbind", strsplit( Taxonomy$V1, ";", fixed = TRUE)) %>%
gsub( "size=([0-9]+)", "\\1", .) %>%
data.frame( ., do.call( "rbind", strsplit( Taxonomy$V2, ";", fixed = TRUE)), stringsAsFactors = F) %>%
apply(., 2, function(x) gsub( "\\(.*\\)", "", x)) %>%
replace(., . == "unclassified", "Unclassified") ->
Taxonomy
colnames( Taxonomy ) <- c( "OTU", "Frequency", "Domain", "Phylum", "Class", "Order", "Family", "Genus" )
# rownames(Taxonomy) <- colnames(Rock_weathering_OTUmat)
rownames(Taxonomy) <- Taxonomy[, 1]
# generate phyloseq object
Rock_dust <- phyloseq(otu_table(Rock_weathering_OTUmat, taxa_are_rows = FALSE),
tax_table(Taxonomy[, -c(1, 2)]),
sample_data(Metadata)
)
# Reorder factors for plotting
sample_data(Rock_dust)$Source %<>% fct_relevel("Limestone", "Dolomite", "Dust", "Loess soil")
```
Remove samples not for analysis
```{r remove samples, cache=T}
samples2remove <- c(2, 3, 4, 5, 6, 7, 8, 10, 12)
Rock_dust <- subset_samples(Rock_dust, !grepl(paste(c(sample_names(Rock_dust)[samples2remove]), collapse = "|"), sample_names(Rock_dust)))
Rock_dust <- filter_taxa(Rock_dust, function(x) sum(x) > 0, TRUE)
domains2remove <- c("", "Eukaryota", "Unclassified")
classes2remove <- c("Chloroplast")
families2remove <- c("Mitochondria")
Rock_weathering_filt <- subset_taxa(Rock_dust, !is.na(Phylum) &
!Domain %in% domains2remove &
!Class %in% classes2remove &
!Family %in% families2remove)
```
First let's explore the prevalence of different taxa in the database.
```{r explore prevalence, cache=T}
prevdf <- apply(X = otu_table(Rock_weathering_filt),
MARGIN = ifelse(taxa_are_rows(Rock_weathering_filt), yes = 1, no = 2),
FUN = function(x){sum(x > 0)})
# Add taxonomy and total read counts to this data.frame
prevdf <- data.frame(Prevalence = prevdf,
TotalAbundance = taxa_sums(Rock_weathering_filt),
tax_table(Rock_weathering_filt))
prevdf %>%
group_by(Phylum) %>%
summarise(`Mean prevalence` = mean(Prevalence),
`Sum prevalence` = sum(Prevalence)) ->
Prevalence_phylum_summary
Prevalence_phylum_summary %>%
kable(., digits = c(0, 1, 0)) %>%
kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive"), full_width = F)
prevdf %>%
group_by(Order) %>%
summarise(`Mean prevalence` = mean(Prevalence),
`Sum prevalence` = sum(Prevalence)) ->
Prevalence_Order_summary
Prevalence_Order_summary %>%
kable(., digits = c(0, 1, 0)) %>%
kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive"), full_width = F)
```
Based on that we'll remove all phyla with a prevalence of under 7
```{r remove rare taxa, cache=T}
Prevalence_phylum_summary %>%
filter(`Sum prevalence` < 7) %>%
select(Phylum) %>%
map(as.character) %>%
unlist() ->
filterPhyla
Rock_weathering_filt2 <- subset_taxa(Rock_weathering_filt, !Phylum %in% filterPhyla)
sample_data(Rock_weathering_filt2)$Lib.size <- rowSums(otu_table(Rock_weathering_filt2))
print(Rock_weathering_filt)
print(Rock_weathering_filt2)
```
Plot general prevalence features of the phyla
```{r prevalence phylum, cahce=T, fig.height=12, fig.width=10}
# Subset to the remaining phyla
prevdf_phylum_filt <- subset(prevdf, Phylum %in% get_taxa_unique(Rock_weathering_filt2, "Phylum"))
ggplot(prevdf_phylum_filt,
aes(TotalAbundance, Prevalence / nsamples(Rock_weathering_filt2), color = Phylum)) +
# Include a guess for parameter
geom_hline(yintercept = 0.05,
alpha = 0.5,
linetype = 2) + geom_point(size = 2, alpha = 0.7) +
scale_x_log10() + xlab("Total Abundance") + ylab("Prevalence [Frac. Samples]") +
facet_wrap( ~ Phylum) + theme(legend.position = "none")
```
Plot general prevalence features of the top 20 orders
```{r prevalence order, cache=T, fig.height=12, fig.width=10}
# Subset to the remaining phyla
prevdf_order_filt <- subset(prevdf, Order %in% get_taxa_unique(Rock_weathering_filt2, "Order"))
# grab the top 30 most abundant orders
prevdf_order_filt %>%
group_by(Order) %>%
summarise(Combined.abundance = sum(TotalAbundance)) %>%
arrange(desc(Combined.abundance)) %>%
.[1:30, "Order"] ->
Orders2plot
prevdf_order_filt2 <- subset(prevdf, Order %in% Orders2plot$Order)
ggplot(prevdf_order_filt2,
aes(TotalAbundance, Prevalence / nsamples(Rock_weathering_filt2), color = Order)) +
# Include a guess for parameter
geom_hline(yintercept = 0.05,
alpha = 0.5,
linetype = 2) + geom_point(size = 2, alpha = 0.7) +
scale_x_log10() + xlab("Total Abundance") + ylab("Prevalence [Frac. Samples]") +
facet_wrap( ~ Order) + theme(legend.position = "none")
```
#### Unsupervised filtering by prevalence
We'll remove all sequences which appear in less than 10% of the samples
```{r}
# Define prevalence threshold as 10% of total samples
prevalenceThreshold <- 0.1 * nsamples(Rock_weathering_filt)
prevalenceThreshold
# Execute prevalence filter, using `prune_taxa()` function
keepTaxa <-
row.names(prevdf_phylum_filt)[(prevdf_phylum_filt$Prevalence >= prevalenceThreshold)]
Rock_weathering_filt3 <- prune_taxa(keepTaxa, Rock_weathering_filt2)
sample_data(Rock_weathering_filt3)$Lib.size <- rowSums(otu_table(Rock_weathering_filt3))
print(Rock_weathering_filt2)
print(Rock_weathering_filt3)
```
This removed `r ntaxa(Rock_weathering_filt2) - ntaxa(Rock_weathering_filt3)` or `r percent(1 - (ntaxa(Rock_weathering_filt3) / ntaxa(Rock_weathering_filt2)))` of the sequences.
### Exploring Rock_dust dataset features
First let's look at the count data distribution
```{r plot abundance, cache=T}
PlotLibDist(Rock_weathering_filt3)
sample_data(Rock_weathering_filt3) %>%
remove_rownames %>%
select(sample_title, Lib.size) %>%
as(., "data.frame") %>%
kable(.) %>%
kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive"), full_width = F)
```
The figure and table indicate only a small deviation in the number of reads per samples.
```{r mod abundance, cache=T, fig.asp=.8}
(mod1 <- adonis(
otu_table(Rock_weathering_filt3) ~ Lib.size,
data = as(sample_data(Rock_weathering_filt3), "data.frame"),
method = "bray",
permutations = 9999
))
PlotReadHist(as(otu_table(Rock_weathering_filt3), "matrix"))
notAllZero <- (rowSums(t(otu_table(Rock_weathering_filt3))) > 0)
meanSdPlot(as.matrix(log2(t(otu_table(Rock_weathering_filt3))[notAllZero, ] + 1)))
```
### Account for variation in library read-depth
We'll use the GMPR method [@chen_gmpr:_2017]
```{r GMPR, cache=T}
Rock_weathering_filt3_GMPR <- Rock_weathering_filt3
Rock_weathering_filt3 %>%
otu_table(.) %>%
t() %>%
as(., "matrix") %>%
GMPR() ->
GMPR_factors
Rock_weathering_filt3 %>%
otu_table(.) %>%
t() %*% diag(1 / GMPR_factors$gmpr) %>%
t() %>%
as.data.frame(., row.names = sample_names(Rock_weathering_filt3)) %>%
otu_table(., taxa_are_rows = FALSE) ->
otu_table(Rock_weathering_filt3_GMPR)
sample_data(Rock_weathering_filt3_GMPR)$Lib.size <- sample_sums(Rock_weathering_filt3_GMPR)
adonis(
otu_table(Rock_weathering_filt3_GMPR) ~ Lib.size,
data = as(sample_data(Rock_weathering_filt3_GMPR), "data.frame"),
method = "bray",
permutations = 9999
)
PlotLibDist(Rock_weathering_filt3_GMPR)
```
```{r GMPR diag plots, cache=T, fig.asp=.8}
PlotReadHist(as(otu_table(Rock_weathering_filt3_GMPR), "matrix"))
notAllZero <- (rowSums(t(otu_table(Rock_weathering_filt3_GMPR))) > 0)
meanSdPlot(as.matrix(log2(t(otu_table(Rock_weathering_filt3_GMPR))[notAllZero, ] + 1)))
```
### Alpha diversity
Calculate and plot alpha diversity mertrics.
```{r alpha-div, cache=T, fig.width=20, fig.height=10}
# non-parametric richness estimates
rarefaction.mat <- matrix(0, nrow = nsamples(Rock_weathering_filt3), ncol = bootstraps)
rownames(rarefaction.mat) <- sample_names(Rock_weathering_filt3)
rich.ests <- list(S.obs = rarefaction.mat, S.chao1 = rarefaction.mat, se.chao1 = rarefaction.mat,
S.ACE = rarefaction.mat, se.ACE = rarefaction.mat)
for (i in seq(bootstraps)) {
sub.OTUmat <- rrarefy(otu_table(Rock_weathering_filt3), min(rowSums(otu_table(Rock_weathering_filt3))))
for (j in seq(length(rich.ests))) {
rich.ests[[j]][, i] <- t(estimateR(sub.OTUmat))[, j]
}
}
Richness <- data.frame(row.names = row.names(rich.ests[[1]]))
for (i in c(1, seq(2, length(rich.ests), 2))) {
S <- apply(rich.ests[[i]], 1, mean)
if (i == 1) {
se <- apply(rich.ests[[i]], 1, function(x) (mean(x)/sqrt(length(x))))
} else se <- apply(rich.ests[[i + 1]], 1, mean)
Richness <- cbind(Richness, S, se)
}
colnames(Richness) <- c("S.obs", "S.obs.se", "S.chao1", "S.chao1.se", "S.ACE", "S.ACE.se")
saveRDS(Richness, file = "Results/Rock_weathering_Richness.Rds")
write.csv(Richness, file = "Results/Rock_weathering_Richness.csv")
ses <- grep("\\.se", colnames(Richness))
Richness[, ses] %>%
gather(key = "est.se") -> se.dat
Richness[, -unique(ses)] %>%
gather(key = "est") -> mean.dat
n <- length(unique(mean.dat$est))
# diversity indices
diversity.inds <- list(Shannon = rarefaction.mat, inv.simpson = rarefaction.mat, BP = rarefaction.mat)