-
Notifications
You must be signed in to change notification settings - Fork 0
/
sey_git.Rmd
3136 lines (2660 loc) · 159 KB
/
sey_git.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: "Influence of the coral-macroalgal shift on compositions of microbial communities in seaweeds and enteric microbiomes of reef fish in Seychelles"
subtitle : Data processes & analyses
author: |
| Marie-Charlotte, Cheutin^a,1^, Jean-Christophe, Auguet^a^, Sebastien, Villeger^a^, & James, Robinson^b^.
<p> </p>
<font size="2"> ^a^ UMR Marbec,CNRS,IRD, Ifremer, Université de Montpellier, Batiment 24, Campus Triolet, Montpellier,34090 France</font>
<font size="2"> ^b^ Lancaster University, Lancaster, U.K </font>
<p> </p>
<font size="3"> ^1^To whom correspondence should be addressed. E-mail: mccheutin@yahoo.es</font>
abstract: "Workflow to generate phyloseq objects, analyze data, and create figures for the influence of the coral-macroalgal shift in Seychelles on microbiomes of seaweeds and gut if reef fish. Here we report both methods and results in plain text and R code. You can choose to show all code or hide the code using the button in the upper right hand corner of the front page (default is hide) as well as download the .Rmd file to tweak the code."
date: "`r Sys.Date()`"
output:
html_document:
keep_md: false
code_folding: hide
code_download: true
toc: TRUE
toc_float: true
toc_depth: 3
theme: cosmo
highlight: haddock
df_print: paged
number_sections: false
pdf_document: default
#cool_themes: default, cerulean, cosmo, darkly, flatly, journal, lumen, sandstone, simplex, spacelab, united, yeti
---
```{r setup, eval = F}
knitr::opts_chunk$set(eval = FALSE)
remove(list = ls())
cran_packages <- c("knitr", "phyloseqGraphTest", "phyloseq", "shiny", "microbiome",
"tidyverse", "miniUI", "caret", "pls", "e1071", "ggplot2",
"randomForest","entropart", "vegan", "plyr", "dplyr", "here",
"ggrepel", "nlme", "R.utils", "gridExtra","grid", "googledrive",
"googlesheets", "phangorn", "devtools", "rmarkdown", "sys",
"reshape2", "devtools", "PMA","structSSI","ade4", "ape",
"Biostrings", "igraph", "ggnetwork", "intergraph", "ips",
"scales", "kableExtra", "pgirmess", "treemap", "knitr","kableExtra",
"rstudioapi" ,"data.table","DT","pander","formatR","grDevices","svgPanZoom",
"RCurl","plotly","pairwiseAdonis", "stringr")
github_packages <- c("jfukuyama/phyloseqGraphTest")
bioc_packages <- c("phyloseq", "genefilter", "impute", "dada2", "DECIPHER")
# Install CRAN packages (if not already installed)
#Some packages would be not availbale for your R version
inst <- cran_packages %in% installed.packages()
if (any(! inst)) {
install.packages(cran_packages[!inst], repos = "http://cran.rstudio.com/") }
#
inst <- github_packages %in% installed.packages()
if (any(! inst)) {
devtools::install_github(github_packages[!inst]) }
# Load libraries
sapply(c(cran_packages, bioc_packages), require, character.only = TRUE)
sessionInfo()
set.seed(1000)
```
```{r set_wd, echo=FALSE}
knitr::opts_knit$set(root.dir = getwd())
path = getwd()
# This will setwd to wherever the .Rmd file is opened.
dir_sample_selection <- paste0(path,"/analyses/01_select_samples/")
dir_seq_processing <- paste0(path,"/analyses/02_process_sequences/")
dir_taxa_assign <- paste0(path,"/analyses/03_assign_taxonomy/")
dir_data_cleaning <- paste0(path, "/analyses/04_data_cleaning/")
dir_primers <- paste0(path,"/dir_data_source/primers_sequences/")
dir_refdb <- paste0(path,"/dir_data_source/reference_databases/")
dir_fastq_source <- paste0(path,"/dir_data_source/sequences/")
```
```{r mkdirs, echo=FALSE, eval=F}
dir.create(dir_sample_selection, recursive = TRUE)
dir.create(dir_seq_processing, recursive = TRUE)
dir.create(dir_taxa_assign, recursive = TRUE)
dir.create(dir_data_cleaning, recursive = TRUE)
dir.create(dir_primers, recursive = TRUE)
dir.create(dir_refdb, recursive = TRUE)
dir.create(dir_fastq_source ,recursive =T)
```
***
## Preamble
<style>
div.blue { background-color:#FBDFB4; border-radius: 5px; padding: 20px;}
</style>
<div class = "blue">
<font size="4">This document is **interactive**. You can **sort and scroll** through most of the tables and the **phylogenetic tree is zoomable**. In the upper right hand corner of the front page is a `Code` button. Use this to show or hide all the code in the document (default is hide) as well as download the `.Rmd` file which you can use to extract the code. Data products from the final paper are highlighted in <font size="3" color="red">Red</font>.</font>
</div>
### Definitions & Abbreviations
* [Amplicon Sequence Variant](https://www.nature.com/articles/ismej2017119){target="_blank"} (**ASV**): Exact sequence variant---analogous to an OTU---but with single nucleotide resolution.
* [Core microbiome](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4817671/){target="_blank"}
(**Core**): A dispersion index is calculated for each ASV as the ratio of the variance to the mean abundance multiplied by the occurrence :
$$ID_x = \frac{Variance_x}{\sum_{Abondance_x}}$$
where $ID_x$ is the index of dispersion of the $ASV_x$.
Each calculated index was compared to a Poisson distribution ([Magurran & Henderson, 2003](https://www.nature.com/articles/nature01547)), and tested whether they were included between the 2.5% and 97,5% confidence interval of the Khi^2^ distribution (Krebs, 1999).
* [**IR & HR**]{target="_blank"}: Impacted Reef and Healthy Reef conditions where **IRs** are reefs which have undergone a macroalgae invasion while **HRs** are reefs with a pre-bleaching disturbance state.
### Study goals
1. Describe the distribution of the sampled fish and environmental pieces between reef conditions.
2. Assess the taxonomic composition of intestinal communities from reef fish and from algae (turf and *Sargassum*).
3. Analyse the potential effect of the coral-macroalgal shift on their microbial communities.
4. Identify which determinants are the drivers of the microbial composition of the enteric microbiome of the reef fish.
***
<a id="back to top"></a>
## Workflow overview
#### [Part I: DADA2 process](#Part I: DADA2 process)
The obtained reads from the sequencing platform (Genotoul, Toulouse) were demultiplexed and linkers with primers sequences were removed before being processed through [DADA2 pipeline](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4927377/){target="_blank"} (Callahan et al., 2016). Briefly, sequences were trimmed and filtered for quality, dereplicated and inferred in ASVs (Glassman & Martiny, 2018). Forward and reverse ASVs were merged and finally generated a count table where chimera were identified and removed. The taxonomy assignment was performed using the [SILVA reference database (*release 123*)](https://academic.oup.com/nar/article/41/D1/D590/1069277){target="_blank"} (Quast et al., 2013). A [phyloseq](https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0061217){target="_blank"} object (McMurdie & Holmes, 2013) was generated for further statistical analysis.
#### [Part II: Phyloseq process](#Part II: Phyloseq process)
To minimize the effect of contamination during the dissection, extraction and amplification steps, the ASVs taxonomically assigned to Eukarya Kingdom (< 0.1%), the organelles reads (Chloroplast and Mitochondria ) and to 40 kit contaminant genus described in [Salter et al. (2014)](https://bmcbiol.biomedcentral.com/articles/10.1186/s12915-014-0087-z) were removed from the database. Because of the high variability of sequencing depth, tables of ASVs were normalized based on the lowest number of sequences for each compartment (gut, macroalgae and turf). Thus, this part create several phyloseq object in order to use for the alpha and beta diversity.
#### [Part III: Fish Community Composition between Reefs](#Part III: Fish Community Composition between Reefs)
Before analyzing the microbial compositions, we assess the host distribution between reefs. The macroalga shift has already been study to alter fish communities and trophic structure ([Burkepile & Hay, (2008)](https://www.pnas.org/content/105/42/16201) ; [Nyström et al., (2008)](https://link.springer.com/article/10.1007%2Fs00338-008-0426-z)). We first analyze our sampling results in order to underpinned the previous observations and to understand how microbiome is adapted to the health reef status.
#### [Part IV: Determination and description of the enteric and algal core microbiomes](#Part IV: Determination and description of the enteric and algal core microbiomes)
We first describe the core microbiome as microbiome constituted by theoritical permanent ASVs. I a first step, enteric and macro-algal core bacteriomes were independently identified by examining the species abundance distribution (SAD) patterns of each ASV and by partitioning the SAD into core and satellite ASVs ([Magurran & Henderson, 2003](https://www.nature.com/articles/nature01547)). For this purpose, the index of dispersion for each ASV was calculated as the ratio of the variance to the mean abundance (VMR) multiplied by the occurrence.
$$ID_x = \frac{Variance_x}{\sum_{Abondance_x}}$$
where $ID_x$ is the index of dispersion of the $ASV_x$.
This index was used to model whether lineages follow a Poisson distribution (i.e., stochastic distribution), falling between the 2.5 and 97.5% confidence interval of the χ2 distribution (Krebs, 1999).
Concerning the alpha diversity, tables were normalized with the abundance of the minimal sampling size. Richness observed and Shannon index were calculated and compared between both compartment. Then, the beta diversity was calculated with the normalized tables for both cores. A blast on the different ASVs was also made and ploted through Itol in order to determine the origin of the ASVs in the enteric and algal cores. Also, to detect the taxa descriptor of each compartment, we proceeded to a Linear Discriminant analyses on LefSe to detect which ASVs are biomarkers of each compartments ([Segata et al., 2011](https://www.ncbi.nlm.nih.gov/pubmed/21702898)).
#### [Part V: Influence of the coral-macrolagal shift on microbial compositions](#Part V: Influence of the coral-macrolagal shift on microbial compositions)
In this part, we treated the main issue comparing the environmental samples and enteric core microbiomes from HRs and IRs with alpha diversity and beta diversity with PERMANOVA.
Concerning the enteric microbiome, our sampling size permited to test four species (*Aprion virescens*, *Scarus ghobban*, *Lethrinus mahsena* and *Lethrinus enigmaticus*), two genus (*Lethrinus* sp., *Scarus* sp.) and one family (Lutjanidae).
#### [Part VI: Other drivers of enteric microbial communities](#Part VI: Other drivers of enteric microbial communities)
Finally, in order to determine which determinants are the drivers of the microbial composition of the enteric microbiome of the reef fish, we tested the effect of the phylogeny and the diet by comparing the herbivore and the invertivores. As for the [**Part IV**](#Part IV: Compositions of the microbiomes of *Sargassum*, turf and core gut), we generated a LDA in order to detect the microbial taxa biomarkers for each diet.
> Ps: All tables and figures presented below were possibly modify before to be insert in the publication. We also include many additional data productes that were not part of the original publication.
***
<a id="Part I: DADA2 process"></a>
## Part I: DADA2 process
[back to top](#back to top)
#### Preparation of your sequence
First, you need to load the original R1 R2 reads in the **/dir_fastq_source** folder. Then, download the [SILVA database references](https://zenodo.org/record/1172783#.XpSB25MzZQI) into the **/dir_ref_db** folder. Concerning the primers **515F-Y** & **926R** used for this publication, their sequences are written right here. You can also write a .txt files for each primer you used and load it in the **/dir_primers** folder to call them when you need it.
```{r primers description}
primer_515FY <- "GTGYCAGCMGCCGCGGTAA"
primer_926R <- "CCGYCAATTYMTTTRAGTTT"
```
We need to read the folders which contain our sequences,primers sequences, environmental dataset and references.
```{r ref_folder, eval=FALSE}
library(stringr)
nms_seq_runs <- list.files(dir_fastq_source)
paths_seq_runs <- list.files(dir_fastq_source, full.names = TRUE) %>% setNames(nms_seq_runs)
nms_refdb <- list.files(dir_refdb)
paths_refdb <- list.files(dir_refdb, full.names = TRUE) %>% setNames(nms_refdb)
nms_primers <- list.files(dir_primers)
paths_primers <- list.files(dir_primers, full.names = TRUE) %>% setNames(nms_primers)
```
You have R1 and R2 reads with the corresponding sequencing names which can be very ugly.
First, get the list of your samples and exctract the sample names:
```{r samples_list and names , eval=F}
fns <- sort(list.files(dir_sample_selection, full.names = TRUE))
fns <- fns[str_detect(basename(fns), ".fastq")]
fns_R1 <- fns[str_detect(basename(fns), "R1")]
fns_R2 <- fns[str_detect(basename(fns), "R2")]
if(length(fns_R1) != length(fns_R2)) stop("Forward and reverse files do not match.")
sample_names <- sapply(strsplit(basename(fns_R1), "_"), `[`, 1)
sample_names
```
Once sample names cut, you can remove the primer sequence from your data by "counting" the number of nucleotides of each primer. Because nucleotides maybe me flowing, it not advised to remove the sequence of the primer by its nucleotide composition.
```{r remove_primer_seq , eval = F}
library(readr)
primer_set_fwd <- read_lines(paste0(dir_primers, "primer_", "515F-Y" , ".txt"))
primer_set_rev <- read_lines(paste0(dir_primers, "primer_", "926R", ".txt"))
primer_length_fwd <- str_length(primer_set_fwd[2])
primer_length_rev <- str_length(primer_set_rev[1])
# You can also use the sequence of the {r primers description}
```
#### Quality profiles and filter/trim the sequences
Now you can plot the quality profiles of your reads (which is usely better on the R1) in order to truncate the sequences before quality drastically decrease. Then, you can filter your sequences and trim the primer length.
```{r Quality profiles and filtering , eval = F}
dir_quality_plots <- paste0(dir_seq_processing, "/quality_pdf/plots/")
dir_create(dir_quality_plots , recursive = T)
qual_R1 <- plotQualityProfile(fns_R1[1])
qual_R2 <- plotQualityProfile(fns_R2[1])
ggsave(qual_R1, file = paste0(dir_quality_plots , "quality_profile_R1.png"))
ggsave(qual_R2, file = paste0(dir_quality_plots, "quality_profile_R2.png"))
filt_R1 <- str_c(dir_filtered, sample_names, "_R1_filt.fastq")
filt_R2 <- str_c(dir_filtered, sample_names, "_R2_filt.fastq")
names(filt_R1) <- sample_names
names(filt_R2) <- sample_names
set.seed(1000)
out <- filterAndTrim(fns_R1, filt_R1, fns_R2, filt_R2, truncLen=c(240,240),
maxN=0, maxEE=c(2,2), truncQ=2, trimLeft=c(primer_length_fwd,primer_length_rev) , rm.phix=TRUE,
compress=TRUE, multithread=TRUE)
head(out)
sample_names <- sapply(strsplit(basename(filt_R1), "_"), `[`, 1) # Assumes filename = samplename_XXX.fastq.gz
sample_namesR <- sapply(strsplit(basename(filt_R2), "_"), `[`, 1) # Assumes filename = samplename_XXX.fastq.gz
if(!identical(sample_names, sample_namesR)) stop("Forward and reverse files do not match.")
names(filt_R1) <- sample_names
names(filt_R2) <- sample_names
set.seed(1000)
```
Finally, you can learn the error rates for both reads and save them.
```{r Learn the error rate, eval = F}
errF <- learnErrors(filt_R1,nbases=1e8, multithread=TRUE)
errR <- learnErrors(filt_R2, nbases=1e8, multithread=TRUE)
plotErrors_F <- plotErrors(errF, nominalQ=TRUE)
plotErrors_R <- plotErrors(errR, nominalQ=TRUE)
ggsave(plotErrors_F, file = paste0(dir_quality_plots , "plotErrors_F.png"))
ggsave(plotErrors_R, file = paste0(dir_quality_plots, "plotErrors_R.png"))
```
> Ps: If you have big data, please proceed directly at the [Part Ib: DADA2 process for BIG DATA](# Part Ib: DADA2 process for BIG DATA).
#### Dereplication and merging sequences
Now, we dereplicate the filtered reads in order to infer them in dada file to merge.
```{r Dereplication & Inference , eval = F}
#Dereplication step
derepFs <- derepFastq(filt_R1, verbose=TRUE)
derepRs <- derepFastq(filt_R2, verbose=TRUE)
names(derepFs) <- sample_names
names(derepRs) <- sample_names
# Inference step
dadaFs <- dada(derepFs, err=errF, multithread=TRUE, pool = T)
dadaRs <- dada(derepRs, err=errR, multithread=TRUE, pool = T)
dadaFs[[1]]
dadaRs[[1]]
# Merging step
mergers <- mergePairs(dadaFs, derepFs, dadaRs, derepRs, verbose=TRUE)
head(mergers[[1]])
```
Now, we can construct our sequence table "seqtab" and remove chimeras. It is recommandable to track the reads through the pipeline process
```{r construct sequence table & chimeras removing, eval = F}
seqtab <- makeSequenceTable(mergers)
row.names(seqtab) = sample_names
dim(seqtab)
table(nchar(getSequences(seqtab)))
seqtab.nochim <- removeBimeraDenovo(seqtab, method="consensus", multithread=TRUE, verbose=TRUE)
dim(seqtab.nochim)
sum(seqtab.nochim)/sum(seqtab)
saveRDS(seqtab.nochim, paste0(dir_seq_processing,"seqtab.nochim.rds"))
# ____ Track reads through the pipeline ----
getN <- function(x) sum(getUniques(x))
track <- cbind(out, sapply(dadaFs, getN), sapply(mergers, getN), rowSums(seqtab), rowSums(seqtab.nochim))
colnames(track) <- c("input", "filtered", "denoised", "merged", "tabled", "nonchim")
rownames(track) <- sample_names
head(track)
save(track, file = "track_515F-Y_926R.RData")
```
***
### Part Ib: DADA2 process for BIG DATA
[back to top](#back to top)
These chunks are highly recommendable if you have a huge mount of sequences !
```{r Derep & Inference , eval = F}
mergers <- vector("list", length(sample_names))
names(mergers) <- sample_names
for(sam in sample_names) {
cat("Processing:", sam, "\n")
derepFs <- derepFastq(filt_R1[[sam]])
ddF <- dada(derepFs, err=errF, multithread=TRUE)
derepRs <- derepFastq(filt_R2[[sam]])
ddR <- dada(derepRs, err=errR, multithread=TRUE)
merger <- mergePairs(ddF, derepFs, ddR, derepRs)
mergers[[sam]] <- merger
}
rm(derepFs); rm(derepRs)
```
Now the construction of the sequence table
```{r construct sequence table and chimeras removing, eval = F}
seqtab <- makeSequenceTable(mergers)
row.names(seqtab) = sample_names
dim(seqtab)
table(nchar(getSequences(seqtab)))
saveRDS(seqtab, paste0(dir_seq_processing,"seqtab.rds"))
# If processing a single sample, remove the sapply calls: e.g. replace sapply(dadaFs, getN) with getN(dadaFs)
colnames(track) <- c("input", "filtered", "tabled")
rownames(track) <- sample_names
head(track)
save(track, file = "table_track_A515F-Y_926R.RData")
```
And remove chimeras as the other part :
```{r Remove chimeras, eval= F}
seqtab.nochim <- removeBimeraDenovo(seqtab, method="consensus", multithread=TRUE, verbose=TRUE)
dim(seqtab.nochim)
sum(seqtab.nochim)/sum(seqtab)
saveRDS(seqtab.nochim, paste0(dir_seq_processing,"seqtab.nochim.rds"))
```
***
#### Taxonomy assignment
You have already load the SILVA ref files, then you have to assign from them the sequence tables
```{r Tax assignment, eval = F}
load(dir_seq_processing , "seqtab.nochim.rds")
path_reference_db <- paste0(dir_refdb, "silva_nr_v132_train_set.fa.gz")
path_species_db <- paste0(dir_refdb, "silva_species_assignment_v132.fa.gz")
taxaRC <- assignTaxonomy(seqtab.nochim, path_reference_db, tryRC=TRUE)
taxaSp <- addSpecies(taxaRC, path_species_db) # This step can be very long
taxa.print <- taxaSp # Removing sequence rownames for display only
rownames(taxa.print) <- NULL
head(taxa.print)
saveRDS(seqtab.nochim,taxaRC, taxaSp, file= paste0(dir_seq_processing,"dada2_files.rds"))
```
***
<a id="Part II: Phyloseq process"></a>
## Part II: Phyloseq process
[back to top](#back to top)
Now you can create your phyloseq object with your filtered and assigned sequences. Before running the phyloseq process, you need to clean your worspace in order to free the r stack memory
```{r setup2 , echo = F, warning=F, message = F, results = F}
knitr::opts_chunk$set(eval = FALSE)
remove(list = ls())
cran_packages <- c("knitr", "phyloseqGraphTest", "phyloseq", "shiny", "microbiome",
"tidyverse", "miniUI", "caret", "pls", "e1071", "ggplot2",
"randomForest","entropart", "vegan", "plyr", "dplyr", "here",
"ggrepel", "nlme", "R.utils", "gridExtra","grid", "googledrive",
"googlesheets", "phangorn", "devtools", "rmarkdown", "sys",
"reshape2", "devtools", "PMA","structSSI","ade4", "ape",
"Biostrings", "igraph", "ggnetwork", "intergraph", "ips",
"scales", "kableExtra", "pgirmess", "treemap", "knitr","kableExtra",
"rstudioapi" ,"data.table","DT","pander","formatR","grDevices","svgPanZoom",
"RCurl","plotly","pairwiseAdonis", "stringr")
github_packages <- c("jfukuyama/phyloseqGraphTest")
bioc_packages <- c("phyloseq", "genefilter", "impute", "dada2", "DECIPHER")
# Install CRAN packages (if not already installed)
#Some packages would be not availbale for your R version
inst <- cran_packages %in% installed.packages()
if (any(! inst)) {
install.packages(cran_packages[!inst], repos = "http://cran.rstudio.com/") }
#
inst <- github_packages %in% installed.packages()
if (any(! inst)) {
devtools::install_github(github_packages[!inst]) }
# Load libraries
sapply(c(cran_packages, bioc_packages), require, character.only = TRUE)
sessionInfo()
set.seed(1000)
```
And set_wd again
```{r set_wd2, echo = F, eval = T}
knitr::opts_knit$set(root.dir = getwd())
path = getwd()
# This will setwd to wherever the .Rmd file is opened.
dir_sample_selection <- paste0(path,"/analyses/01_select_samples/")
dir_seq_processing <- paste0(path,"/analyses/02_process_sequences/")
dir_taxa_assign <- paste0(path,"/analyses/03_assign_taxonomy/")
dir_data_cleaning <- paste0(path, "/analyses/04_data_cleaning/")
dir_primers <- paste0(path,"/dir_data_source/primers_sequences/")
dir_refdb <- paste0(path,"/dir_data_source/reference_databases/")
dir_fastq_source <- paste0(path,"/dir_data_source/sequences/")
```
#### Phyloseq object creation
We can create our phyloseq object from the seqtab.nochim file created previously.
```{r phyloseq_creation , eval= F}
load(paste0(dir_taxa_assign,"dada2_files.rds"))
load(paste0(dir_taxa_assign,"seqtab.nochim_515F-Y.926R.RData"))
ps <- phyloseq(otu_table(seqtab.nochim, taxa_are_rows=FALSE),tax_table(taxaRC))
# You can use tax_table(taxaSp) if you need the assignment until species level
```
Now, we will modify our table with ASVs names
```{r ASVs names, eval = F}
dna <- Biostrings::DNAStringSet(taxa_names(ps))
names(dna) <- taxa_names(ps)
ps <- merge_phyloseq(ps, dna)
taxa_names(ps) <- paste0("ASV", seq(ntaxa(ps)))
ps
save(ps, taxaRC,seqtab.nochim, seqtab, file=paste0(dir_taxa_assign ,"ps_515F-Y.926R.RData"))
# First results
ntaxa(ps)
nsamples(ps)
sample_names(ps)[1:5]
rank_names(ps)
otu_table(ps)[1:5, 1:5]
tax_table(ps)[1:5, 1:6]
```
#### Presentation of the envdata
The envdata is constituted of the sampling data for the gut, algae and turf samples.
* [**Tax_information**]{target="_blank"} : The informations concerning the species are written in different ways with **tax1** as the Species genus, **tax2** as the Species_genus nomenclature, **tax3** as the SPG_x which is the corresponding two first letters of the species and the first of the genus followed by the *x* of the sampled individuals in this species. The **type**, **lineage**, **Order**, **Family** ,**Genus** and **Species** are mentioned.
* [**Diet_information**]{target="_blank"}: The Diet is mentionned at high scale with the **diet3** and at granulous scales following the ecological traits in [Mouillot et al., (2014)](https://www.pnas.org/content/111/38/13757). The **diet4** mentionned the difference in the herbivory for the Scaridae, Acanthuridae and Siganidae species. Also, the trophic position is mentionned with [the FishBase reference](https://www.fishbase.se/search.php).
* [**Individual_information**]{target="_blank"}: For each individual, the weight **mass**, total **length**, **gut mass** and **sex** were obtained.
* [**Site_information**]{target="_blank"}: **Site** with the **GPS coordonates** were taken and the **geomorphology** were attributed to the condition of the reef.
```{r envdata , eval = T, warning = FALSE, fig.align = "center"}
envdata <- read.csv2(paste0(dir_refdb, "env.csv"))
colnames(envdata)[1] = "ID"
datatable(envdata[-c(3,6,10, 12)], rownames = FALSE, width = "100%",
colnames = c("ID", "Species","Species number" ,"Compartment","Order","Family","Genus","Diet abreviation","Diet High scale","Diet Low scale","Trophic position", "Mass (g)","Total Length (cm)","Gut mass (g)","Sex","Site","Reef condition","GPS latitude","GPS longitude", "Island", "Substrat"),
caption = htmltools::tags$caption(style = "caption-side:
bottom; text-align: left;",
"Table: ",
htmltools::em("Sample presentation.")),
extensions = "Buttons",
options = list(columnDefs =
list(list(className = "dt-left", targets = 0)),
dom = "Blfrtip", pageLength = 5,
lengthMenu = c(5, 10, 25, 50),
buttons = c("csv", "copy"),
scrollX = TRUE, scrollCollapse = TRUE))
```
It's just an parenthesis for ordering envdata depending of your phyloseq objects. It is a step a bit borring but necessary if your env file is not synchro with your phyloseq object, meaning that the samples names in your env file are not the same that your sample names in the phyloseq object.
First, we will order the names
```{r Order the names , eval = F}
load(paste0(dir_taxa_assign, "dada2_files.RData"))
nochim_names <- rownames(seqtab.nochim)
env_names <- as.character(envdata$ID)
```
Now, the aim is to have exactly the same names in the phyloseq object and in the env table.
```{r T or F , eval=F }
lecture <- cbind(sort(nochim_names),sort(env_names))
identical(lecture[,1], lecture[,2])
```
If it's **True**, you're names are the same, directly pass to the merging step; If **False**, you have to replace the correct names. Also, you have to check your env file with the names of your fish species, genus or family which could be incorrect.
```{r check the names of the tax fish, eval= F}
levels(factor(envdata$family))
levels(factor(envdata$species))
```
#### Merging data
Now that the seqtab and the envdata are corresponding, we will merge them into phyloseq object.
```{r Merge envdata and phyloseq, eval=F}
load(paste0(dir_taxa_assign,"ps_515F-Y.926R.RData"))
envdata <- read.csv2(paste0(dir_refdb, "env.csv"))
colnames(envdata)[1] = "ID"
DAT <- sample_data(envdata)
DAT
sort(sample_names(DAT)) == sort(sample_names(ps)) # must be true to be merged
ps1<- merge_phyloseq(ps, DAT)
ps1
save(ps1, envdata,file=paste0(dir_taxa_assign ,"ps1_515F-Y.926R.RData"))
```
Plot the sample minimum ASV
```{r sample minimum ASV , eval = F}
min(rowSums(ps1@otu_table@.Data))
readsumsdf = data.frame(nreads = sort(taxa_sums(ps1),TRUE), sorted = 1:ntaxa(ps1), type = "ASVs")
readsumsdf = rbind(readsumsdf, data.frame(nreads = sort(sample_sums(ps1), TRUE), sorted = 1:nsamples(ps1), type = "Samples"))
title = "Total number of reads"
pdf(file = paste0(dir_quality_plots, "total_number_of_reads.pdf"), he = 7, wi = 7)
p = ggplot(readsumsdf, aes(x = sorted, y = nreads)) + geom_bar(stat = "identity")
p + ggtitle(title) + scale_y_log10() + facet_wrap(~type, 1, scales = "free")
dev.off()
```
#### Phyloseq creation
We will filter our ps1 to only keep the **Prokaryotes**
```{r Prokaryotes_selection, eval = F}
load(paste0(dir_taxa_assign, "ps1_515F-Y.926R.RData"))
ps_sey_proka <- subset_taxa(ps_sey , Kingdom %in% c("Archaea", "Bacteria"))
save(ps_sey_proka, file = paste0(dir_taxa_assign, "ps_sey_proka.RData"))
```
Then, we will obtain the phylogenetic distances between ASVs
The tree was obtained after aligning the sequences on mothur and was names "Sey.tree" and was load in the *\dir_taxa_assign* folder. The assignment was made against the ARB database available on SILVA database reference (v132) and proceeded on [**Mothur**](https://aem.asm.org/content/75/23/7537) platform.
```{r read_tree , eval = F}
sey_tree <- read.tree(paste(dir_taxa_assign, "Sey.tree"))
sey_tree2 <- root(sey_tree, "ASV40619", resolve.root = T)
sey_tree2 <- drop.tip(sey_tree2,"ASV40619" ) # To delete the outgroup ASV
library(picante)
cal1<-makeChronosCalib(sey_tree2, node = "root", age.min = 1, age.max = 1, interactive = FALSE, soft.bounds = FALSE) #calibration for ultrametric branchs.
sey_chronogramme<-chronos(sey_tree2, lambda=0, model = "discrete", cal=cal1, quiet = FALSE, control=chronos.control(nb.rate.cat=1))
save(sey_chronogramme ,file = paste0(dir_taxa_assign ,"sey_chronogramme.Rdata"))
ps_sey_tree <- merge_phyloseq(ps_sey_proka, sey_tree2)
save(ps_sey_tree, file = paste0(dir_taxa_assign, "ps_sey_tree.RData"))
```
Now that the phyloseq is only made by Prokaryotes which phylogenetic distances are associated, we will finally filter all organels (Chloroplast and Mitochondria) and potential contaminants of the exctraction kits and steps of amplification as mentionned in [Salter et al., 2014](https://bmcbiol.biomedcentral.com/articles/10.1186/s12915-014-0087-z).
#### Clean the phyloseq object
```{r Filter the contaminants and organels, eval = F}
cont_list <- read.csv("/Users/marie-charlottecheutin/Drive/Thesis/Seychelles/WP5.3_data/data_sources/reference_databases/list_potential_contaminants.csv")
contaminant <- cont_list$Genus
sey_final <- subset_taxa(ps_sey_tree, Order != "Chloroplast")
sey_final <- subset_taxa(sey_final , Family != "Mitochondria")
sey_contaminant <- subset_taxa(sey_final , Genus %in% contaminant)
save(sey_contaminant , file = paste0(dir_taxa_assign, "sey_contaminant.Rdata"))
sey_final <- subset_taxa(sey_final , !Genus %in% contaminant)
save(sey_final, file = paste0(dir_taxa_assign,"sey_final.RData"))
seyrff_final <- prune_samples(sample_sums(sey_final) >= min(sample_sums(sey_final)) , sey_final)
seyrff_final <- rarefy_even_depth(seyrff_final, sample.size = min(sample_sums(sey_final)))
save(seyrff_final, file = paste0(dir_taxa_assign, "seyrff_final.RData"))
```
Now we have the final phyloseq for all the samples, we can subset the phyloseq object for the gut, the algae and the turf and rarefy them. To be sure that the minimal abundance of the data set is enough to capture all the diversity, we use the function **ggrare()**
```{r ggrare function, eval = T}
ggrare <- function(physeq_object, step = 10, label = NULL, color = NULL, plot = TRUE, parallel = FALSE, se = TRUE) {
x <- methods::as(phyloseq::otu_table(physeq_object), "matrix")
if (phyloseq::taxa_are_rows(physeq_object)) { x <- t(x) }
## This script is adapted from vegan `rarecurve` function
tot <- rowSums(x)
S <- rowSums(x > 0)
nr <- nrow(x)
rarefun <- function(i) {
cat(paste("rarefying sample", rownames(x)[i]), sep = "\n")
n <- seq(1, tot[i], by = step)
if (n[length(n)] != tot[i]) {
n <- c(n, tot[i])
}
y <- vegan::rarefy(x[i, ,drop = FALSE], n, se = se)
if (nrow(y) != 1) {
rownames(y) <- c(".S", ".se")
return(data.frame(t(y), Size = n, Sample = rownames(x)[i]))
} else {
return(data.frame(.S = y[1, ], Size = n, Sample = rownames(x)[i]))
}
}
if (parallel) {
out <- parallel::mclapply(seq_len(nr), rarefun, mc.preschedule = FALSE)
} else {
out <- lapply(seq_len(nr), rarefun)
}
df <- do.call(rbind, out)
# Get sample data
if (!is.null(phyloseq::sample_data(physeq_object, FALSE))) {
sdf <- methods::as(phyloseq::sample_data(physeq_object), "data.frame")
sdf$Sample <- rownames(sdf)
data <- merge(df, sdf, by = "Sample")
labels <- data.frame(x = tot, y = S, Sample = rownames(x))
labels <- merge(labels, sdf, by = "Sample")
}
# Add, any custom-supplied plot-mapped variables
if ( length(color) > 1 ) {
data$color <- color
names(data)[names(data) == "color"] <- deparse(substitute(color))
color <- deparse(substitute(color))
}
if ( length(label) > 1 ) {
labels$label <- label
names(labels)[names(labels) == "label"] <- deparse(substitute(label))
label <- deparse(substitute(label))
}
p <- ggplot2::ggplot(data = data,
ggplot2::aes_string(x = "Size",
y = ".S",
group = "Sample",
color = color))
p <- p + ggplot2::labs(x = "Sequence Sample Size", y = "Species Richness")
if (!is.null(label)) {
p <- p + ggplot2::geom_text(data = labels,
ggplot2::aes_string(x = "x",
y = "y",
label = label,
color = color),
size = 4, hjust = 0)
}
p <- p + ggplot2::geom_line()
if (se) { ## add standard error if available
p <- p +
ggplot2::geom_ribbon(ggplot2::aes_string(ymin = ".S - .se",
ymax = ".S + .se",
color = NULL,
fill = color),
alpha = 0.2)
}
if (plot) {
plot(p)
}
invisible(p)
}
```
And now use it and create the phyloseq objects
#### Subset the phyloseq objects
```{r phyloseq subset, eval= T, warning = FALSE,message = F, results = "hide"}
load(paste0(dir_taxa_assign, "sey_final.RData"))
# Fish ps
sey_gut <- subset_samples(sey_final, type == "gut")
sey_gut <- prune_taxa(names(which(colSums(sey_gut@otu_table)>0)), sey_gut)
save(sey_gut, file = paste0(dir_taxa_assign, "sey_gut.RData"))
sort(sample_sums(sey_gut))
set.seed(10000)
p_gut <- ggrare(sey_gut, step = 500, color = "geomorpho", label = "tax1", se = FALSE)
seyrff_gut <- prune_samples(sample_sums(sey_gut) >= min(sample_sums(sey_gut)) , sey_gut)
seyrff_gut <- rarefy_even_depth(seyrff_gut, sample.size = min(sample_sums(sey_gut)))
save(seyrff_gut, file = paste0(dir_taxa_assign, "seyrff_gut.RData"))
# Algae ps
sey_algae <- subset_samples(sey_final, tax1 %in% c("macroalgae", "turf"))
sey_algae <- prune_taxa(names(which(colSums(sey_algae@otu_table)>0)), sey_algae)
save(sey_algae, file = paste0(dir_taxa_assign, "sey_algae.RData"))
set.seed(10000)
p_algae <- ggrare(sey_algae, step = 500, color = "geomorpho", label = "tax1", se = FALSE)
seyrff_algae <- prune_samples(sample_sums(sey_algae) >= min(sample_sums(sey_algae)) , sey_algae)
seyrff_algae <- rarefy_even_depth(seyrff_algae, sample.size = min(sample_sums(sey_algae)))
save(seyrff_algae, file = paste0(dir_taxa_assign, "seyrff_algae.RData"))
```
***
<a id="Part III: Fish Community Composition between Reefs"></a>
## Part III: Fish Community Composition between Reefs
[back to top](#back to top)
Here again, we will remove all the object to clean the memory
```{r setup3 , echo = F , eval = T, message= F,warning=F, results= F}
knitr::opts_chunk$set(eval = FALSE)
remove(list = ls())
cran_packages <- c("knitr", "phyloseqGraphTest", "phyloseq", "shiny", "microbiome",
"tidyverse", "miniUI", "caret", "pls", "e1071", "ggplot2",
"randomForest","entropart", "vegan", "plyr", "dplyr", "here",
"ggrepel", "nlme", "R.utils", "gridExtra","grid", "googledrive",
"googlesheets", "phangorn", "devtools", "rmarkdown", "sys",
"reshape2", "devtools", "PMA","structSSI","ade4", "ape",
"Biostrings", "igraph", "ggnetwork", "intergraph", "ips",
"scales", "kableExtra", "pgirmess", "treemap", "knitr","kableExtra",
"rstudioapi" ,"data.table","DT","pander","formatR","grDevices","svgPanZoom",
"RCurl","plotly","pairwiseAdonis", "stringr")
github_packages <- c("jfukuyama/phyloseqGraphTest")
bioc_packages <- c("phyloseq", "genefilter", "impute", "dada2", "DECIPHER")
# Install CRAN packages (if not already installed)
#Some packages would be not availbale for your R version
inst <- cran_packages %in% installed.packages()
if (any(! inst)) {
install.packages(cran_packages[!inst], repos = "http://cran.rstudio.com/") }
#
inst <- github_packages %in% installed.packages()
if (any(! inst)) {
devtools::install_github(github_packages[!inst]) }
# Load libraries
sapply(c(cran_packages, bioc_packages), require, character.only = TRUE)
sessionInfo()
set.seed(1000)
```
And set_wd again
```{r set_wd3, echo = F, eval = T, warning=F, message = F}
knitr::opts_knit$set(root.dir = getwd())
path = getwd()
# This will setwd to wherever the .Rmd file is opened.
dir_sample_selection <- paste0(path,"/analyses/01_select_samples/")
dir_seq_processing <- paste0(path,"/analyses/02_process_sequences/")
dir_taxa_assign <- paste0(path,"/analyses/03_assign_taxonomy/")
dir_data_cleaning <- paste0(path, "/analyses/04_data_cleaning/")
dir_primers <- paste0(path,"/dir_data_source/primers_sequences/")
dir_refdb <- paste0(path,"/dir_data_source/reference_databases/")
dir_fastq_source <- paste0(path,"/dir_data_source/sequences/")
```
In this is part, we will focus on our sampling dataset and analyze the distribution of the hosts between the IRs and HRs.
```{r load_files, eval = T, results="hide", warning= F}
envdata <- read.csv2(paste0(dir_refdb, "env.csv"))
colnames(envdata)[1] = "ID"
load(paste0(dir_taxa_assign, "sey_gut.RData"))
load(paste0(dir_taxa_assign, "sey_final.RData"))
```
We will first write the table of the species and their corresponding diet.
```{r table_sp_diet, eval= T, warning = FALSE, fig.align = "center", message=F}
diet_sp <- as.data.frame(table(envdata$diet4, envdata$tax1))[which(as.data.frame(table(envdata$diet4, envdata$tax1))[,3]> 0),][,c(1,2)]
sp_reef <- table(envdata$tax1, envdata$geomorpho)
sp_reef <- cbind(as.data.frame(sp_reef[,1]), as.data.frame(sp_reef[,2]))
table_diet_sp <- cbind(diet_sp[,2],diet_sp[,1],sp_reef[,c(1,2)])
table_to_print <- rbind(table_diet_sp[-c(26,37),], table_diet_sp[c(26,37),])
datatable(table_to_print, rownames = F, width = "100%",
colnames = c("Species", "Diet", "HR","IR"),
caption = htmltools::tags$caption(style = "caption-side:
bottom; text-align: left;",
"Table: ",
htmltools::em("Sampling table of the species and diet between reefs.")),
extensions = "Buttons",
options = list(columnDefs =
list(list(className = "dt-left", targets = 0)),
dom = "Blfrtip", pageLength = 5,
lengthMenu = c(5, 10, 25, 50),
buttons = c("csv", "copy"),
scrollX = TRUE, scrollCollapse = TRUE))
```
##### PCoA on fish community
The distribution of the sampling set is a first result showing the influence of the shift on the fish communities. How are they distributed?
```{r PCoA_family, eval= T , warning = F, message= F, fig.align= "center"}
samp_data <- envdata[envdata$type=="gut",]
fam_tab <- table(samp_data$site,samp_data$family)
# Transform to log
fam.log <- log1p(fam_tab) # Equivalent: log(fam_tab + 1)
# Principal coordinate analysis and simple ordination plot
fam.D <- vegdist(fam.log, "bray")
res <- pcoa(fam.D)
#res$values
biplot(res, fam.log)
#round(res$values$Relative_eig[1]*100, 1) # 57.8 %
#round(res$values$Relative_eig[2]*100, 1) # 26 %
site1 <- c("C1","C2","C3","C4", "M1","M2","M3")
site2 <- c(rep("coral", 4), rep("macroalgal",3))
site_data <- cbind(site1,site2)
colnames(site_data) <- c("site", "geomorpho")
site_data <- as.data.frame(site_data)
adonis(fam.D ~ geomorpho, data = site_data)
beta_reef <- betadisper(fam.D, site_data$geomorpho)
permutest(beta_reef)
```
Now, we will do the same on trophic srtucture with the diet
```{r PCoA_diet,eval= T , warning = F, message= F, fig.align="center"}
samp_data <- envdata[envdata$type=="gut",]
diet_tab <- table(samp_data$site,samp_data$diet4)
# Transform to log
diet.log <- log1p(diet_tab) # Equivalent: log(diet_tab + 1)
# Principal coordinate analysis and simple ordination plot
diet.D <- vegdist(diet.log, "bray")
res <- pcoa(diet.D)
#res$values
par(mfrow=c(1,2))
biplot(res, diet.log)
#round(res$values$Relative_eig[1]*100, 1) # 74.1 %
#round(res$values$Relative_eig[2]*100, 1) # 17.8 %
site1 <- c("C1","C2","C3","C4", "M1","M2","M3")
site2 <- c(rep("coral", 4), rep("macroalgal",3))
site_data <- cbind(site1,site2)
colnames(site_data) <- c("site", "geomorpho")
site_data <- as.data.frame(site_data)
adonis(diet.D ~ geomorpho, data = site_data)
beta_reef <- betadisper(diet.D, site_data$geomorpho)
permutest(beta_reef)
```
Because we will focus our sutdy on herbivores and invertivores, we need to know if families are equally distributed.
```{r PCoA_inv,eval= T , warning = F, message= F,fig.align="center"}
samp_data_inv <- samp_data[samp_data$diet4 == "Mobile invertebrate",]
fam_tab <- table(samp_data_inv$site,samp_data_inv$family)
# Transform to log
fam.log <- log1p(fam_tab) # Equivalent: log(fam_tab + 1)
# Principal coordinate analysis and simple ordination plot
fam.D <- vegdist(fam.log, "bray")
res <- pcoa(fam.D)
#res$values
biplot(res, fam.log)
#round(res$values$Relative_eig[1]*100, 1) # 57.8 %
#round(res$values$Relative_eig[2]*100, 1) # 26 %
site1 <- c("C1","C2","C3","C4", "M1","M2","M3")
site2 <- c(rep("coral", 4), rep("macroalgal",3))
site_data <- cbind(site1,site2)
colnames(site_data) <- c("site", "geomorpho")
site_data <- as.data.frame(site_data)
adonis(fam.D ~ geomorpho, data = site_data)
beta_reef <- betadisper(fam.D, site_data$geomorpho)
permutest(beta_reef)
```
***
<a id="Part IV: Determination and description of the enteric and algal core microbiomes"></a>
## Part IV: Determination and description of the enteric and algal core microbiomes
[back to top](#back to top)
### Colors
Microbial community of fish is very high and it is very difficult to discern less than 10 taxa. That's why, we kept the same color for the same taxa, in order to be able to compare the graphs between compartemtn, diet or fish families. Of course, if your are only interested in some taxa, better choose few colors. For the bigger table (*i.e* tax table at Order level), **distinctColorPalette()** could be very useful but be awared that colors are not repeated. Here is the code :
```{r colors , echo = T , eval = T}
phylum_colors <- c('Acidobacteria'='lavenderblush4',
'Actinobacteria'='darkblue',
'Armatimonadetes'='cadetblue3',
'Bacteroidetes'='cornflowerblue',
'Calditrichaeota'='azure3',
'Chloroflexi'='#DCE1D2',
'Cyanobacteria'='#DE6554',
'Dadabacteria'='brown2',
'Deferribacteres'='darkslategray1',
'Deinococcus-Thermus'='salmon4',
'Dependentiae'='sandybrown',
'Epsilonbacteraeota'='darkslateblue',
'Elusimicrobia'='plum1',
'Euryarchaeota'='hotpink4',
'Firmicutes'='brown4',
'Fusobacteria'='orange',
'Gemmatimonadetes'='darkolivegreen',
'Kiritimatiellaeota'='darkkhaki',
'Marinimicrobia_(SAR406_clade)'='darkgoldenrod4',
'Latescibacteria'='darkseagreen2',
'Lentisphaerae'='darkseagreen4',
'Patescibacteria'='darkturquoise',
'Planctomycetes'='darkslategray',
'Proteobacteria'='aquamarine4',
'Spirochaetes'='darkolivegreen3',
'Tenericutes'='#CA8EA7',
'Thaumarchaeota'='gold3',
'Verrucomicrobia'='darkgreen',
'WPS-2'='thistle2',
'Other'= 'black',
'Z-Other' = 'black')
class_colors <- c("Acidimicrobiia"="darksalmon",
"Acidobacteriia"="lavenderblush4",
"Actinobacteria"="darkblue",
"Alphaproteobacteria"="lightseagreen",
"Babeliae"="peachpuff",
"Anaerolineae"="tomato2",
"Bacilli"="brown4",
"Bacteroidia"="cornflowerblue",
"Brachyspirae"="darkolivegreen2",
"Campylobacteria"="royalblue",
"Clostridia"="orange3",
"Coriobacteriia"="deepskyblue4",
"Deferribacteres"="darkslategray1",
"Deinococci"="skyblue3",
"Deltaproteobacteria"="skyblue4",
"Erysipelotrichia"="yellow",
"Fusobacteriia"="orange",
"Fimbriimonadia" = "darkseagreen",
"Gammaproteobacteria"="aquamarine4",
"Kiritimatiellae"="darkgray",
"Lentisphaeria"="darkseagreen4",
"Microgenomatia"="seashell3",
"Mollicutes"="#CA8EA7",
"Negativicutes"="palevioletred4",
"Nitrososphaeria"="sandybrown",
"Oxyphotobacteria"="#DE6554",
"Phycisphaerae"="rosybrown4",
"Planctomycetacia"="darkslategray",
"Rhodothermia"="cornsilk3",
"Spirochaetia"="darkolivegreen3",
"Thermoanaerobaculia"="purple",
"Thermoleophilia"="deeppink4",
"Verrucomicrobiae"="darkgreen")
#library(randomcoloR)
#n <- length(levels(core_physeq_order$Order))
#order_colors <- distinctColorPalette(n)
```
***
Let's analyze our data previously proceeded. In order to descrimine which ASVs are rare (transients) and which would be considered as permanent (core), we use a dispersion index for each ASV and compare it at the Poisson distribution to determine which ASVs are signifcantly randomly distributed (transiant) and which are not (core) following the method of [Fillol et al. (2016)](https://www.nature.com/articles/ismej2015143).
***
### Part IVa: Enteric core microbiome
[back to top](#back to top)
We create a new folder for the enteric microbiome of reef fish
and determine the core.
```{r enteric core wd, echo = T, eval = T, warning=F, message = F}
dir_data_cleaning <- paste0(path, "/analyses/04_data_cleaning/Fish/Core/")
dir.create(dir_data_cleaning, recursive = T)
load(paste0(dir_taxa_assign, "sey_gut.RData"))
load(paste0(dir_taxa_assign, "seyrff_gut.RData"))
```
#### Core determination
```{r enteric core determination, echo = T, eval = T, warning=F, message = F}
library(labdsv)
otu_table <- seyrff_gut@otu_table@.Data
abuoccplot_otu <- abuocc(otu_table)
#sub_objects of abuocc objects
str(abuoccplot_otu)
# transform spc.plt vector into table in order to calculate specific richness
richness_otu <- data.frame(abuoccplot_otu$spc.plt)
# occurence of each OTU
otu_occurence <- data.frame(abuoccplot_otu$plt.spc)
mean.abun_otu <- colSums(otu_table)/otu_occurence
square_otu <- otu_table^2
ss_otu <- data.frame(colSums(square_otu))
# Variance calculation
variance_otu=ss_otu/otu_occurence-mean.abun_otu^2
disp_otu <- (variance_otu/mean.abun_otu)*otu_occurence
# IC calculation for Poisson distribution using Chi square distribution (value and formula within Zar p574)
library(epitools)
poisic_otu = pois.exact(otu_occurence, conf.level = 0.95)
gut_dstat_otu <- cbind(mean.abun_otu, disp_otu, otu_occurence, poisic_otu)
names(gut_dstat_otu) <- c("average","disp", "occurence", "x", "pt", "rate", "lower", "upper", "prob")
save(gut_dstat_otu, file=paste0(dir_data_cleaning, "gut_sey_dstat_asv.RData"))
# Selection of core ASVs
gut_sey_core_otu <- gut_dstat_otu[gut_dstat_otu$disp > gut_dstat_otu$upper,]
gut_sey_core_otu <- na.exclude(gut_sey_core_otu)
gut_tax <- data.frame(seyrff_gut@tax_table@.Data)
gut_sey_core_otu$tax <- gut_tax[rownames(gut_tax) %in% row.names(gut_sey_core_otu),6]
gut_sey_core_otu$phylum <- gut_tax[rownames(gut_tax) %in% row.names(gut_sey_core_otu),2]
save(gut_sey_core_otu, file = paste0(dir_data_cleaning,"gut_sey_core_otu.Rdata"))
sey_gut_core <-prune_taxa(rownames(gut_sey_core_otu), seyrff_gut)
save(sey_gut_core, file = paste0(dir_data_cleaning, "sey_gut_core.RData"))
```
To blast the reads of the core, we need to generate a fasta file with the function `writeXStringSet()`.
```{r fasta enteric file, echo = F, eval = F, warning=F, message = F}
gut_names <- colnames(sey_gut_core@otu_table)
gut_tree <- subset_taxa(sey_gut_core, rownames(sey_gut_core@tax_table) %in% gut_names)
gut_tree
Biostrings::writeXStringSet(sey_gut_core@refseq, file = paste0(dir_data_cleaning,"sey_gut_core.fasta"))
```
#### Composition of the core
```{r gut composition stackplot, echo = F, eval = T, warning=F, message = F}
library(dplyr)
gut_core_order <- sey_gut_core %>%
tax_glom(taxrank = "Order") %>% # agglomerate at phylum level
transform_sample_counts(function(x) {x/sum(x)} ) %>% # Transform to rel. abundance
psmelt() %>% # Melt to long format
filter(Abundance > 0.02) %>% # Filter out low abundance taxa
arrange(Order)
save(gut_core_order , file = paste0(dir_data_cleaning, "gut_core_order.RData"))
```