-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFullAnalysis.Rmd
2643 lines (2174 loc) · 103 KB
/
FullAnalysis.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: "Stability of Vaginal microbiota during pregnancy and its importance for early infant microbiota using ASV"
output:
html_document:
toc: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = F, eval = F,warning = F,message = F,fig.width = 15, fig.height = 15,
fig.align = 'center')
```
# 0 - Prep
Data for this project is from the COPSAC~2010~ cohort of 711 children / mother pairs.
In this project we include vaginal samples (week 24 and week 36), airway samples (1 week, 1 month, and 3 months), and fecal samples (1 week, 1 month, and 1 year) for all mother-child dyads which include a week 36 vaginal sample (665 mothers and 651 children). We describe the vaginal microbiome development from mid pregnancy (week 24) to late pregnancy (week 36), and the transfer to the airways and gut of the children in the first year of life. A special focus is on the differences between transfer to vaginal and sectio born children.
## 0.1 - Load libraries
```{r libraries, eval=TRUE}
rm(list = ls())
library(tidyverse)
library(cluster)
library(fpc)
library(broom)
library(knitr)
library(ggrepel)
library(RColorBrewer)
library(cowplot)
library(ggtree)
library(ggalluvial)
library(vegan)
library(phyloseq)
library(foreach)
library(RVAideMemoire)
library(pheatmap)
library(ggplotify)
library(reshape2)
```
## 0.2 Download main data and scripts
```{r download_main_data, eval=TRUE}
### setting up the ASV data to match the formating of the initial ASV based analysis
if (!file.exists("COPSACbirthmicrobiome_ASV.RData") download.file('https://github.com/mortenarendt/VagTransfer/blob/master/COPSACbirthmicrobiome_ASV.RData',paste(getwd(),'COPSACbirthmicrobiome_ASV.RData',sep = '/'))
if (!file.exists("getTransferStats.R") download.file('https://github.com/mortenarendt/VagTransfer/blob/master/getTransferStats.R',paste(getwd(),'getTransferStats.R',sep = '/'))
if (!file.exists("getWinnerStats.R") download.file('https://github.com/mortenarendt/VagTransfer/blob/master/getWinnerStats.R',paste(getwd(),'getWinnerStats.R',sep = '/'))
if (!file.exists("inferenceTransferStat.R") download.file('https://github.com/mortenarendt/VagTransfer/blob/master/inferenceTransferStat.R',paste(getwd(),'inferenceTransferStat.R',sep = '/'))
if (!file.exists("transferFunctions.R") download.file('https://github.com/mortenarendt/VagTransfer/blob/master/transferFunctions.R',paste(getwd(),'transferFunctions.R',sep = '/'))
# clean environment
rm(list = ls(all = TRUE))
```
**COPSACbirthmicrobiome_ASV.RData** contains the phyloseq object that is used for all subsequent analysis and with this the whole analysis can be easily replicated
## 0.3 Download precalculated data
To reduce the computational requirements during this analysis, we have precalculated the most computer intensive parts and if these are downloaded the calculations can be skipped. This means that you can either run this code chunk or all following code chunks which are currently set not to be evaluated.
```{r download_main_data, eval=FALSE}
### setting up the ASV data to match the formating of the initial ASV based analysis
download.file('http://mibi.galaxy.bio.ku.dk/martin/VagTransfer/CommunityStateTypes.RData',paste(getwd(),'CommunityStateTypes.RData',sep = '/'))
download.file('http://mibi.galaxy.bio.ku.dk/martin/VagTransfer/ORresults.RData',paste(getwd(),'ORresults.RData',sep = '/'))
download.file('http://mibi.galaxy.bio.ku.dk/martin/VagTransfer/OrderRatioSTATs.RData',paste(getwd(),'OrderRatioSTATs.RData',sep = '/'))
download.file('http://mibi.galaxy.bio.ku.dk/martin/VagTransfer/OrderRatioSTATs_split.RData',paste(getwd(),'OrderRatioSTATs_split.RData',sep = '/'))
download.file('http://mibi.galaxy.bio.ku.dk/martin/VagTransfer/OrdinationRes.RData',paste(getwd(),'OrdinationRes.RData',sep = '/'))
download.file('http://mibi.galaxy.bio.ku.dk/martin/VagTransfer/Stability_w24_to_2w6_permresults.RData',paste(getwd(),'Stability_w24_to_2w6_permresults.RData',sep = '/'))
download.file('http://mibi.galaxy.bio.ku.dk/martin/VagTransfer/Winnerstats.RData',paste(getwd(),'Winnerstats.RData',sep = '/'))
download.file('http://mibi.galaxy.bio.ku.dk/martin/VagTransfer/air_OrdinationRes.RData',paste(getwd(),'air_OrdinationRes.RData',sep = '/'))
download.file('http://mibi.galaxy.bio.ku.dk/martin/VagTransfer/air_taxglm.RData',paste(getwd(),'air_taxglm.RData',sep = '/'))
download.file('http://mibi.galaxy.bio.ku.dk/martin/VagTransfer/fec_OrdinationRes.RData',paste(getwd(),'fec_OrdinationRes.RData',sep = '/'))
download.file('http://mibi.galaxy.bio.ku.dk/martin/VagTransfer/fec_taxglm.RData',paste(getwd(),'fec_taxglm.RData',sep = '/'))
download.file('http://mibi.galaxy.bio.ku.dk/martin/VagTransfer/phyX_cst.RData',paste(getwd(),'phyX_cst.RData',sep = '/'))
download.file('http://mibi.galaxy.bio.ku.dk/martin/VagTransfer/vag_taxglm.RData',paste(getwd(),'vag_taxglm.RData',sep = '/'))
download.file('http://mibi.galaxy.bio.ku.dk/martin/VagTransfer/weighted_permutation_results_onesided.RData',paste(getwd(),'weighted_permutation_results_onesided.RData',sep = '/'))
# clean environment
rm(list = ls(all = TRUE))
```
## 0.4 - Overview of samples, read counts and observed richness
```{r sample_overview,eval=TRUE}
load('COPSACbirthmicrobiome_ASV.RData')
SD <- sample_data(phyX)
levels(SD$Time) <- list(Week_24 = 24, Week_36 = 36, One_week = "1w", One_month = "1m", Three_months = "3m", One_year = "1y")
levels(SD$Type) <- list(Vaginal = "V", Fecal = "F", Airway = "T")
print("Phyloseq object used")
print(phyX)
print("sample count per time and type")
tb0 <- data.frame(table(SD$Type,SD$Time))
colnames(tb0) <- c("Compartment", "Time", "Samples")
tb0.order <- tb0[order(tb0$Compartment),]
tb0.order[tb0.order$Samples != 0,]
fecX <- subset_samples(phyX,Type=='F')
airX <- subset_samples(phyX,Type=='T')
vagX <- subset_samples(phyX,Type=='V')
df_type_stat <- data.frame(
nfec = apply(otu_table(fecX)>0,1,sum),
nair = apply(otu_table(airX)>0,1,sum),
nvag = apply(otu_table(vagX)>0,1,sum))
print("ASVs observed per compartment")
apply(df_type_stat>0,2,sum)
# get number of identified ASV's in each compartment
df <- data.frame(depth = sample_sums(phyX),
nobserved = apply(otu_table(phyX)>0,2,sum),
sample_data(phyX))
ggplot(data = df, aes(x = depth, fill = Type:Time)) +
geom_histogram()+
scale_x_log10() +
facet_wrap(~Type:Time)
tb <- df %>% group_by(Type,Time) %>%
summarise(median_count = median(depth),
mean_count = mean(depth),
sd_count = sd(depth),
q25_count= quantile(depth)[2],
q75_count= quantile(depth)[4],
median_observed = median(nobserved),
mean_observed = mean(nobserved),
sd_observed = sd(nobserved),
min_observed = min(nobserved),
max_observed = max(nobserved),
q25_observed = quantile(nobserved)[2],
q75_observed = quantile(nobserved)[4]
)
tb.type <- df %>% group_by(Type) %>%
summarise(median_count = median(depth),
mean_count = mean(depth),
sd_count = sd(depth),
q25_count= quantile(depth)[2],
q75_count= quantile(depth)[4],
median_observed = median(nobserved),
mean_observed = mean(nobserved),
sd_observed = sd(nobserved),
min_observed = min(nobserved),
max_observed = max(nobserved),
q25_observed = quantile(nobserved)[2],
q75_observed = quantile(nobserved)[4]
)
kable(tb.type,caption = 'Summary stats for compartment', digits = 1)
kable(tb,caption = 'Summary stats for compartment/timepoint', digits = 1)
# clean environment
rm(list = ls(all = TRUE))
```
# 1 - Vaginal microbiome
## 1.1 - Data prep
```{r prep_vaginal,eval=FALSE}
load('COPSACbirthmicrobiome_ASV.RData')
# ASV level
vagX.raw <- subset_samples(phyX,Type=='V')
vagX <- prune_taxa(taxa_sums(vagX.raw) > 0, vagX.raw)
vagX.ra <- transform_sample_counts(vagX, function(x) x/sum(x))
vagX.r <- rarefy_even_depth(vagX, 2000, rngseed = 2)
vagX.transformed <- transform_sample_counts(vagX.r, function(x) x/sum(x))
# Phylum level
vagXphy <- tax_glom(vagX,'Phylum')
taxa_names(vagXphy) <- tax_table(vagXphy)[,2]
vagXphy.ra <- transform_sample_counts(vagXphy, function(x) x/sum(x))
# Genus level
vagXgenus <- tax_glom(vagX,'Genus_simple')
taxa_names(vagXgenus) <- tax_table(vagXgenus)[,6]
vagXgenus.ra <- transform_sample_counts(vagXgenus, function(x) x/sum(x))
# Save phyloseq objects
save(file = './vag_taxglm.RData',list = c('vagX','vagXphy','vagXgenus','vagX.ra','vagXphy.ra','vagXgenus.ra','vagX.r'))
# Beta diversity
vag.jsd <- distance(vagX.transformed, method="jsd")
cl <- parallel::makeCluster(4)
doParallel::registerDoParallel(cl)
vag.WUnifrac <- UniFrac(vagX.prune, weighted=TRUE, parallel = TRUE)
vag.all.nmds <- metaMDS(vag.WUnifrac, k = 4, trymax = 100)
vag.all.jsd.nmds <- metaMDS(vag.jsd, k = 5, trymax = 100)
# Save distance matrices and ordinations
save(file = './OrdinationRes.RData',list = c('vag.WUnifrac','vag.all.nmds','vag.all.jsd.nmds','vag.jsd'))
# clean environment
rm(list = ls(all = TRUE))
```
**vag_taxglm.RData** contains phyloseq objects with vaginal samples at phylum, genus and ASV level for both read counts and relative abundances, as well as a rarefied (2000 reads/sample) at ASV level.
**OrdinationRes.RData** contains weighted UniFrac distances and jensen-Shannon divergence, as well as NMDS ordinations of both
## 1.2 - Observed vaginal ASV's:
The distribution of the vaginal reads are here summarized on phylum, genus and individual ASV level.
```{r composition_vaginal,eval=TRUE}
load('./vag_taxglm.RData')
df2 <- data.frame(tax_table(vagXphy.ra), taxprc = 100*taxa_sums(vagXphy.ra)/length(sample_names(vagXphy.ra)))
df3 <- data.frame(tax_table(vagXgenus.ra),taxprc = 100*taxa_sums(vagXgenus.ra)/length(sample_names(vagXgenus.ra)))
df3$Genus <- df3$Genus_simple
df4 <- data.frame(tax_table(vagX.ra),taxprc = 100*taxa_sums(vagX.ra)/length(sample_names(vagX.ra)))
df.richness <- data.frame(Included = c("All", "> 0.01%", "> 0.1%","> 1%"),
Phylum = c(nrow(df2),sum(df2$taxprc > 0.0001),sum(df2$taxprc > 0.001),sum(df2$taxprc > 0.01)),
Genus = c(nrow(df3),sum(df3$taxprc > 0.0001),sum(df3$taxprc > 0.001),sum(df3$taxprc > 0.01)),
ASV = c(nrow(df4),sum(df4$taxprc > 0.0001),sum(df4$taxprc > 0.001),sum(df4$taxprc > 0.01)))
# Count of ASV and species in vaginal samples
kable(df.richness, row.names = F,digits = 1, caption = 'Count of phyla, genera, and ASV in vaginal samples')
# Top 6 dominating phyla (prc abundance)
kable(head(df2[order(df2$taxprc,decreasing = T),c("Kingdom","Phylum","taxprc")]), row.names = F,digits = 1, caption = 'Average abundance according to phylym')
# Top 6 dominating (genera prc abundance)
kable(head(df3[order(df3$taxprc,decreasing = T),c("Kingdom","Phylum","Class","Order","Family","Genus","taxprc")]), row.names = F,digits = 1, caption = 'Average abundance according to genus')
# Top 6 donimating species (prc abundance)
kable(head(df4[order(df4$taxprc,decreasing = T),c("Kingdom","Phylum","Class","Order","Family","Genus","Species","name","taxprc")]), row.names = F,digits = 1, caption = 'Average abundance according to ASV')
# clean environment
rm(list = ls(all = TRUE))
```
The BLAST results and best matching species for each of the top 6 dominant ASVs can be found in the .xlsx file 88TaxToBlast.xlsx**
## 1.3 - Community State Types
The vaginal microbiome is _not_ a smooth continoum, but a set of very well defined clusters, here refered to as Community State Types (CST), and a few less well defined clusters. These are identified by clustering of _all_ the samples based on Jensen Shannon Divergence as beta diversity measure. Partitioning around medoids clustering is then performed for a range of possible clusters and the optimal number defined based on various cluster statistics.
### 1.3.1 - Define Community State Types
#### 1.3.1.1 - Find optimal number of clusters
```{r number_of_clusters,eval=T}
load('./OrdinationRes.RData')
#Pam cluster from 3 to 10 clusters to see what fits best
pam.df <- data.frame(pam.03 = pam(vag.jsd, 3)$ clustering,
pam.04 = pam(vag.jsd, 4)$ clustering,
pam.05 = pam(vag.jsd, 5)$ clustering,
pam.06 = pam(vag.jsd, 6)$ clustering,
pam.07 = pam(vag.jsd, 7)$ clustering,
pam.08 = pam(vag.jsd, 8)$ clustering,
pam.09 = pam(vag.jsd, 9)$ clustering,
pam.10 = pam(vag.jsd, 10)$ clustering)
# look at cluster statistics
clust.stat <- data.frame(clustering = colnames(pam.df),
average.between = numeric(length(ncol(pam.df))),
average.within = numeric(length(ncol(pam.df))),
avg.silwidth = numeric(length(ncol(pam.df))),
pearsongamma = numeric(length(ncol(pam.df))),
dunn = numeric(length(ncol(pam.df))),
dunn2 = numeric(length(ncol(pam.df))),
entropy = numeric(length(ncol(pam.df))),
wb.ratio = numeric(length(ncol(pam.df))),
ch = numeric(length(ncol(pam.df))),
widestgap = numeric(length(ncol(pam.df))),
sindex = numeric(length(ncol(pam.df)))
)
for (i in 1:ncol(pam.df)){
tmp <- cluster.stats(vag.jsd,clustering = pam.df[,i],noisecluster = T)
clust.stat[i,] <- c(colnames(pam.df)[i],tmp[c("average.between","average.within","avg.silwidth","pearsongamma","dunn","dunn2","entropy","wb.ratio","ch","widestgap","sindex")])
}
stat.melt <- melt(clust.stat,id.vars = "clustering", variable.name = "stat",value.name = "value")
ggplot(stat.melt, aes(clustering,value)) + geom_bar(stat = "identity") + facet_wrap(facets = "stat", scales = "free") + coord_flip()
# clean environment
rm(list = ls(all = TRUE))
```
Based on the Pearson version of Hubert's gamma coefficient (pearsongamma), average silhouette width (avg.silwidth) and the Calinski and Harabasz index (ch) 5 or 6 clusters is optimal. Considering the Dunn2 index we consider *6* clusters to be optimal. These are refered to as community state types I to V, with IV being split into IV-a and IV-b.
#### 1.3.1.2 - Create CSTs
The ASVs for the top ASVs in each CST are written to **TaxToBlast.xlsx**, Blast results and identified species for each ASV have then been added to this file externally.
```{r create_clusters,eval=FALSE}
load('./vag_taxglm.RData')
load('./OrdinationRes.RData')
# Add clustering
sample_data(vagX)$CST <- pam(vag.jsd, 6)$clustering
sample_data(vagX)$CST <- as.factor(sample_data(vagX)$CST)
# top 100 overall ASVs extracted
ASVtab <- otu_table(vagX.ra) %>% t()
ss <- rank(apply(ASVtab,2,sum))
ss <- max(ss) - ss + 1
df2 <- data.frame(ASVtab[,ss<100], sample_data(vagX))
txtb <- tax_table(vagX) %>% as.data.frame()
txtb$ASV <- rownames(txtb)
tb1ASV <- df2 %>%
gather(ASV,cnt,-(dyadnb:CST)) %>%
left_join(txtb, by = 'ASV') %>%
group_by(dyadnb,Time) %>%
mutate(libsize = sum(cnt),
cnt = cnt / libsize) %>%
ungroup() %>%
group_by(CST,ASV) %>%
summarise(totcnt = mean(cnt)*100) %>%
ungroup() %>%
group_by(CST) %>%
mutate(rnk = rank(totcnt),
rnk = max(rnk)-rnk+1) %>%
arrange(CST,desc(totcnt)) %>%
filter(rnk<6)
kable(tb1ASV,row.names = F,digits = 1, caption = 'Most abundant ASVs in each cluster')
# Identify relevant ASV hashes
asv.keep <- as.character(unique(tb1ASV[tb1ASV$rnk < 4,"ASV"]))
tax.keep <- txtb[txtb$ASV %in% asv.keep,]
rio::export(txtb[txtb$ASV %in% asv.keep,],file = 'TaxToBlast.xlsx')
# Levels of the CST variable is then named based on top 3 ASV in each CST, in accordance with Gajer et al. (2012)
levels(sample_data(vagX)$CST) <- list(CST_I = 3, CST_II = 4, CST_III = 5, CST_IV_a = 2, CST_IV_b = 1, CST_V = 6)
sample_data(vagX.r) <- sample_data(vagX)
# add mothers CST at week 36 to phyX
dyad.cst36 <- sample_data(vagX) %>%
data.frame() %>%
filter(Time == 36) %>%
select(dyadnb,CST)
df.cst <- data.frame(sample_data(phyX))
for (i in 1:nrow(dyad.cst36)){
df.cst$CST_w36[df.cst$dyadnb == as.character(dyad.cst36$dyadnb[i])] <- as.character(dyad.cst36$CST[i])
}
sample_data(phyX) <- df.cst
save(file = "./phyX_cst.RData", list = c('phyX','vagX','vagX.r'))
# clean environment
rm(list = ls(all = TRUE))
```
**phyX_cst.RData** contains the updated phyloseq objects for all samples (phyX), vaginal samples (vagX), and rarefied vaginal samples (vagX.r)
### 1.3.2 - CST composition and stability
#### 1.3.2.1 - Prepare data
```{r CST_prep,eval=FALSE}
load('./vag_taxglm.RData')
load('./phyX_cst.RData') # must be loaded second as it overwrites the initial vagX and vagX.r
# table with alpha diversity measures
cst.alpha <- cbind(data.frame(sample_data(vagX.r)),estimate_richness(vagX.r, measures = c("Observed","Shannon"))[,c("Observed","Shannon")])
cst.alpha.stat <- cst.alpha %>%
group_by(CST) %>%
summarize(Samples = n(),
observed_mean = mean(Observed),
observed_sd = sd(Observed),
SDI_mean = mean(Shannon),
SDI_sd = sd(Shannon))
# table with top dominating taxa / ASVs in each CST
# Phylum
df2 <- data.frame(otu_table(vagXphy.ra) %>% t(), sample_data(vagX))
txtb <- tax_table(vagXphy) %>% as.data.frame()
txtb$ASV <- rownames(txtb)
# tb0 <- df2 %>%
# group_by(dyadnb) %>%
# mutate(rep = n()) %>%
# ungroup() %>%
# group_by(CST) %>%
# summarise(n = n(), n24 = sum(Time==24),n36 = sum(Time==36),
# n_w_rep = sum(rep==2), n24_w_rep = sum(Time==24 & rep==2), n36_w_rep = sum(Time==36 & rep==2))
# tb0$ndyadsame <- c(sum(df2$dyadnb[df2$CST == "CST_I" & df2$Time == 24] %in% df2$dyadnb[df2$CST == "CST_I" & df2$Time == 36]),
# sum(df2$dyadnb[df2$CST == "CST_II" & df2$Time == 24] %in% df2$dyadnb[df2$CST == "CST_II" & df2$Time == 36]),
# sum(df2$dyadnb[df2$CST == "CST_III" & df2$Time == 24] %in% df2$dyadnb[df2$CST == "CST_III" & df2$Time == 36]),
# sum(df2$dyadnb[df2$CST == "CST_IV_a" & df2$Time == 24] %in% df2$dyadnb[df2$CST == "CST_IV_a" & df2$Time == 36]),
# sum(df2$dyadnb[df2$CST == "CST_IV_b" & df2$Time == 24] %in% df2$dyadnb[df2$CST == "CST_IV_b" & df2$Time == 36]),
# sum(df2$dyadnb[df2$CST == "CST_V" & df2$Time == 24] %in% df2$dyadnb[df2$CST == "CST_V" & df2$Time == 36]))
# tb0$prc24dyadsame <- with(tb0, 100*ndyadsame/n24_w_rep)
# tb0$prc36dyadsame <- with(tb0, 100*ndyadsame/n36_w_rep)
tb1 <- df2 %>%
gather(ASV,cnt, -(dyadnb:CST)) %>%
left_join(txtb, by = 'ASV') %>%
group_by(dyadnb,Time) %>%
mutate(libsize = sum(cnt),
cnt = cnt / libsize) %>%
ungroup() %>%
group_by(CST,Phylum) %>%
summarise(totcnt = mean(cnt)*100) %>%
ungroup() %>%
group_by(CST) %>%
mutate(rnk = rank(totcnt),
rnk = max(rnk)-rnk+1) %>%
arrange(CST,desc(totcnt)) %>%
filter(rnk<6)
# Genus
df2 <- data.frame(otu_table(vagXgenus.ra) %>% t(), sample_data(vagX))
txtb <- tax_table(vagXgenus) %>% as.data.frame()
txtb$ASV <- rownames(txtb)
tb1g <- df2 %>%
gather(ASV,cnt,-(dyadnb:CST)) %>%
left_join(txtb, by = 'ASV') %>%
group_by(dyadnb,Time) %>%
mutate(libsize = sum(cnt),
cnt = cnt / libsize) %>%
ungroup() %>%
group_by(CST,Genus_simple) %>%
summarise(totcnt = mean(cnt)*100) %>%
ungroup() %>%
group_by(CST) %>%
mutate(rnk = rank(totcnt),
rnk = max(rnk)-rnk+1) %>%
arrange(CST,desc(totcnt)) %>%
filter(rnk<6)
# ASV
ASVtab <- otu_table(vagX.ra) %>% t()
# top 100 overall
ss <- rank(apply(ASVtab,2,sum))
ss <- max(ss) - ss + 1
df2 <- data.frame(ASVtab[,ss<100], sample_data(vagX))
txtb <- tax_table(vagX) %>% as.data.frame()
txtb$ASV <- rownames(txtb)
tb1ASV <- df2 %>%
gather(ASV,cnt,-(dyadnb:CST)) %>%
left_join(txtb, by = 'ASV') %>%
group_by(dyadnb,Time) %>%
mutate(libsize = sum(cnt),
cnt = cnt / libsize) %>%
ungroup() %>%
group_by(CST,ASV) %>%
summarise(totcnt = mean(cnt)*100) %>%
ungroup() %>%
group_by(CST) %>%
mutate(rnk = rank(totcnt),
rnk = max(rnk)-rnk+1) %>%
arrange(CST,desc(totcnt)) %>%
filter(rnk<6)
colnames(tb1)[3] <- 'Phylum_prc'
colnames(tb1g)[3] <- 'Genus_prc'
colnames(tb1ASV)[3] <- 'ASV_prc'
tb1m <- merge(merge(tb1,tb1g, by = c('CST','rnk')), tb1ASV,by = c('CST','rnk'))
save(file = './CommunityStateTypes.RData',list = c('vagX','tb0','tb1m','cst.alpha','cst.alpha.stat'))
# clean environment
rm(list = ls(all = TRUE))
```
**CommunityStateTypes.RData** contains the necessary data regarding dominant taxa and alpha diversity of the CSTs
#### 1.3.2.2 - Describe CST composition and stability
Figure 1 - A: Boxplot of obserbed richness by CST, B: boxplot of shannon diversity index by CST, C: boxplot of the 2 most dominant ASV in each CST, colored by CST, and D: Alluvial plot with CST.
```{r CST_description,eval=TRUE,fig.cap='Figure 1: A) Boxplot of obserbed richness by CST, B) boxplot of shannon diversity index by CST, C) boxplot of the 2 most dominant ASV in each CST, colored by CST, and D) Alluvial plot with CST.'}
load('./CommunityStateTypes.RData')
# tables
# kable(tb0, caption = 'Sample Distribution, n: number of samples in CST, n_w_rep: number of samples in CST from women with both timepoints represented, n24 / n36: number of samples from week 24 and 36 respectively')
kable(cst.alpha.stat, caption = 'Observed richness and shannon diversity index (SDI) for each CST', digits = 2)
print("Statistical test of alpha diversity by CST")
fit <- aov(Observed ~ CST, data = cst.alpha)
anova(fit)
TukeyHSD(fit)
fit <- aov(Shannon ~ CST, data = cst.alpha)
anova(fit)
TukeyHSD(fit)
kable(tb1m, caption = 'Top five Phylums / Genus / ASVs for each CST', digits = 2)
# fig 1 a (boxplot top ASV)
asv.keep <- as.character(unique(tb1m$ASV[tb1m$rnk < 3]))
vagX.topasv <- prune_taxa(taxa_names(vagX) %in% asv.keep, transform_sample_counts(vagX, function(x) x/sum(x)*100))
top.asv.melt <- psmelt(vagX.topasv)
top.asv.melt$ASV <- top.asv.melt$name
df.labels <- data.frame(ASV = c('Genus_Atopobium_36','Genus_Bifidobacterium_60','Genus_Gardnerella_20','Genus_Gardnerella_40','Genus_Lactobacillus_139','Genus_Lactobacillus_268','Lactobacillus_gasseri_37','Genus_Lactobacillus_323','Genus_Megasphaera_22'),
label = c('A. vaginae','B. longum','G. vaginalis_a','G. vaginalis_b','L. iners','L. jensenii','L. gasseri','L. crispatus','M. massiliensis'))
F1a <- ggplot(top.asv.melt, aes(y = ASV, x = Abundance, alpha = 0.5)) +
geom_boxplot(position =position_dodge2(reverse = TRUE), aes(color = CST)) +
geom_boxplot(position =position_dodge2(reverse = TRUE), aes(fill = CST), outlier.shape = 21) +
scale_fill_brewer(palette = 'Set1') +
scale_color_brewer(palette = 'Set1') +
scale_y_discrete(breaks=df.labels$ASV,labels=df.labels$label) + ylab("") +
theme_bw() + theme(axis.title = element_text(size = 15), axis.text.x = element_text(size = 10),legend.position = 'none',axis.text.y = element_text(face="italic",size = 10)) #+
# fig 1b (Observed)
F1b <- ggplot(cst.alpha, aes(x = CST, y = Observed, alpha = 0.5)) +
geom_boxplot(aes(color = CST)) +
geom_boxplot(aes(fill = CST), outlier.shape = 21) +
scale_fill_brewer(palette = 'Set1') +
scale_color_brewer(palette = 'Set1') +
ylab("Observed richness") + xlab("") +
theme_bw() + theme(axis.title = element_text(size = 15),
axis.text = element_text(size = 10),
axis.text.x=element_blank(),
axis.ticks.x=element_blank(),
legend.position = 'none')
# fig 1c (Shannon)
F1c <- ggplot(cst.alpha, aes(x = CST, y= Shannon, alpha = 0.5)) +
geom_boxplot(aes(color = CST)) +
geom_boxplot(aes(fill = CST), outlier.shape = 21) +
scale_fill_brewer(palette = 'Set1') +
scale_color_brewer(palette = 'Set1') +
ylab("Shannon diversity index") + xlab("") +
theme_bw() + theme(axis.title = element_text(size = 15),
axis.text = element_text(size = 10),
axis.text.x=element_blank(),
axis.ticks.x=element_blank(),
legend.position = 'none')
# fig 1d (allivial plot)
F1d <- sample_data(vagX) %>%
ggplot(data = .,
aes(x = Time, stratum = CST, alluvium = dyadnb,
# weight = 1,
fill = CST, label = CST)) +
geom_flow() +
scale_fill_brewer(palette = 'Set1') +
scale_x_discrete(expand = c(0,0)) +
geom_stratum(alpha = .5) +
# facet_grid(cleandef~trt) +
geom_text(stat = "stratum", size = 3) +
theme_bw() +
xlab('Pregnancy week') +
theme(axis.title = element_text(size = 15), axis.text = element_text(size = 10), legend.position = 'right',panel.grid = element_blank(), panel.border = element_blank())
# fig 1
F1 <- ggdraw() + draw_plot(F1a, 0, 0, 0.4, 1) +
draw_plot(F1b, 0.4, 0.5, 0.2, 0.5) +
draw_plot(F1c, 0.4, 0, 0.2, 0.5) +
draw_plot(F1d, 0.6, 0, 0.4, 1) +
draw_plot_label(c("A", "B","C","D"), c(0,0.4, 0.4, 0.6), c(1,1,0.5,1), size = 15)
pdf('Figure1_CST.pdf',height = 8, width = 12)
F1
dev.off()
print(F1)
# clean environment
rm(list = ls(all = TRUE))
```
#### 1.3.2.3 - Stability between w24 and w36 (Permutational)
In order to test the stability between time points, a permutation procedure is used. Here, the distance based on individual women from week 24 to week 36 are compared with random assignments of pairs.
##### 1.3.2.3.1 - Perform permutation calculations
```{r CST_perm_calc,eval=FALSE}
load('./phyX_cst.RData')
load('./OrdinationRes.RData')
nperm <- 2500
# get dist for all pairs
getDist <- function(x,D){
id <- rownames(D) %in% x$smpname
if (sum(id)==2){
dd <- D[id,id]
dst <- dd[1,2]
}
else {dst <- NA}
return(data.frame(distw24_w36 = dst))
}
sd_vagX <- sample_data(vagX)
sd_vagX$smpname = rownames(sd_vagX)
# Wunifrac
Dwuf <- as.matrix(vag.WUnifrac)
ddfmodel <- sd_vagX %>%
group_by(dyadnb) %>%
do(getDist(x = ., Dwuf)) %>%
left_join(sd_vagX[sd_vagX$Time==24,], by = 'dyadnb')
ddfperm <- c()
for (i in 1:nperm){
print(i)
sd_vagX$dyadnb2 <- sd_vagX$dyadnb
sd_vagX$dyadnb2[sd_vagX$Time==36] <- sample(sd_vagX$dyadnb2[sd_vagX$Time==36])
ddf2 <- sd_vagX %>%
group_by(dyadnb2) %>%
do(getDist(x = ., Dwuf)) %>%
mutate(permutation = i)
ddfperm <- rbind(ddfperm,ddf2)
}
# calculate the statistics
pv <- ddfperm %>%
left_join(ddfmodel, by = c('dyadnb2' = 'dyadnb')) %>%
filter(!is.na(distw24_w36.x) & !is.na(distw24_w36.y)) %>%
group_by(dyadnb2) %>%
summarise(n = n(),
npos = sum(distw24_w36.x < distw24_w36.x),
freq = npos / n) %>%
ungroup %>%
summarise(pv = mean(freq))
dfmodelwuf <- ddfmodel
dfpermwuf <- ddfperm
pv_wuf <- pv
# JSD model
Djsd <- as.matrix(vag.jsd)
ddfmodel <- sd_vagX %>%
group_by(dyadnb) %>%
do(getDist(x = ., Djsd)) %>%
left_join(sd_vagX[sd_vagX$Time==24,], by = 'dyadnb')
ddfperm <- c()
for (i in 1:nperm){
print(i)
sd_vagX$dyadnb2 <- sd_vagX$dyadnb
sd_vagX$dyadnb2[sd_vagX$Time==36] <- sample(sd_vagX$dyadnb2[sd_vagX$Time==36])
ddf2 <- sd_vagX %>%
group_by(dyadnb2) %>%
do(getDist(x = ., Djsd)) %>%
mutate(permutation = i)
ddfperm <- rbind(ddfperm,ddf2)
}
# calculate the statistics
pv <- ddfperm %>%
left_join(ddfmodel, by = c('dyadnb2' = 'dyadnb')) %>%
filter(!is.na(distw24_w36.x) & !is.na(distw24_w36.y)) %>%
group_by(dyadnb2) %>%
summarise(n = n(),
npos = sum(distw24_w36.x < distw24_w36.x),
freq = npos / n) %>%
ungroup %>%
summarise(pv = mean(freq))
dfmodeljsd <- ddfmodel
dfpermjsd <- ddfperm
pv_jsd <- pv
save(file = './Stability_w24_to_2w6_permresults.RData',
list = c('dfmodelwuf','dfpermwuf','pv_wuf','dfmodeljsd','dfpermjsd','pv_jsd'))
# clean environment
rm(list = ls(all = TRUE))
```
**Stability_w24_to_2w6_permresults.RData** contains the permutation results for CST stability
##### 1.3.2.3.2 - CST stability results
```{r CST_stability_output, eval = TRUE}
load('./Stability_w24_to_2w6_permresults.RData')
load('./phyX_cst.RData')
sd_vagX <- sample_data(vagX)
# remove singletons
ttb <- sd_vagX %>%
group_by(dyadnb) %>%
mutate(n = n()) %>%
filter(n==2) %>%
group_by(dyadnb) %>%
mutate(insame = ifelse(length(unique(CST))==1,1,0)) %>%
group_by(CST,Time) %>%
summarise(n = n(),
n_insame = sum(insame),
prc_insame = 100*n_insame/n)
ttb1 <- ttb %>%
filter(Time==24) %>%
ungroup %>%
summarise(n_total = sum(n),
n_insame = sum(n_insame),
n_changed = n_total-sum(n_insame)) %>%
mutate(n_insame = paste(n_insame, " (", format(round(100*n_insame/n_total,1),nsmall = 1),")", sep = ""),
n_changed = paste(n_changed, " (", format(round(100*n_changed/n_total,1),nsmall = 1),")", sep = ""))
ttb2 <- ttb %>%
mutate(n_insame = paste(n_insame, " (", format(round(100*n_insame/n,1),nsmall = 1),")", sep = "")) %>%
select(-prc_insame)
kable(ttb1,caption = 'overall stability descriptives from week 24 and week 36 dependent', digits = 1,
col.names = c("Women", "In same (%)","Changed (%)"))
kable(ttb2,caption = 'CST descriptives from week 24 and week 36 dependent', digits = 1,
col.names = c("CST", "Time point (weeks)", "Women","In same (%)"), align=c("l","c","c","r"))
# prep data
df.cst <- data.frame(sample_data(vagX))
df.dyad <- data.frame(table(df.cst$dyadnb))
df.cst.full <- df.cst[df.cst$dyadnb %in% df.dyad$Var1[df.dyad$Freq == 2],]
df.cst.24 <- df.cst.full[df.cst.full$Time == 24,]
df.cst.36 <- df.cst.full[df.cst.full$Time == 36,]
# Change of CST
for (i in 1:nrow(df.cst.24)){
if (df.cst.24$CST[i] == df.cst.36$CST[df.cst.36$dyadnb == df.cst.24$dyadnb[i]]) df.cst.24$w36[i] <- "same" else df.cst.24$w36[i] <- "changed"
}
print("Pearson's Chi-squared test of CST stability")
chisq.bintest(df.cst.24$w36 ~ df.cst.24$CST,alpha = 0.05)
dfwuf <- dfpermwuf %>%
left_join(dfmodelwuf, by = c('dyadnb2' = 'dyadnb'))
dfjsd <- dfpermjsd %>%
left_join(dfmodeljsd, by = c('dyadnb2' = 'dyadnb'))
DF <- bind_rows(data.frame(dfwuf,method = 'wuf'),data.frame(dfjsd,method = 'jsd')) #%>%
tb <- DF %>%
filter(!is.na(distw24_w36.y) & permutation==1) %>%
group_by(method) %>%
summarise(n= n(), median_dist = median(distw24_w36.y, na.rm = T))
tb_CST <- DF %>%
filter(!is.na(distw24_w36.y) & permutation==1) %>%
group_by(method,CST) %>%
summarise(n= n(), median_dist = median(distw24_w36.y, na.rm = T))
tb_CSTpv <- DF %>%
filter(!is.na(distw24_w36.y) & permutation==1) %>%
group_by(method) %>%
do(kruskal.test(data = .,distw24_w36.y~CST) %>% tidy %>% select(-method))
tb2 <- DF %>%
filter(!is.na(distw24_w36.x) & !is.na(distw24_w36.y)) %>%
group_by(method, permutation) %>%
summarise(median_permdist = median(distw24_w36.x)) %>%
ungroup %>%
left_join(tb) %>%
group_by(method) %>%
summarise(
n = n[1],
median_dist = median_dist[1],
median_permdist = mean(median_permdist),
R = median_permdist / median_dist,
pv = sum(1+(median_permdist<median_dist)) / (1+n()))
kable(tb2, caption = 'Stability between week 24 and week 36 assigned as median distance between pairs as compared with mismatched pairs (# permutations = 2500)', digits = 5)
kable(tb_CST,caption = 'Stability between week 24 and week 36 dependent on week 24 CST', digits = 4)
ggplot(data = tb_CST, aes(CST, median_dist, fill = CST)) +
geom_bar(stat = 'identity') +
scale_fill_brewer(palette = 'Set1') +
facet_wrap(~method, scales = 'free') +
theme_bw() +
theme(legend.position = 'none')
kable(tb_CSTpv,caption = 'Inference (kruskal walis) for differences in stability between week 24 and week 36 dependent on week 24 CST', digits = 100)
# clean environment
rm(list = ls(all = TRUE))
```
The statistics indicate that stability depends on CST.
## 1.4 Beta diversity of vaginal
Here PCoA plots show the distirbution of the samples based on CST and beta diversity metric.
Clearly, some of the CST are more well defined than others. E.g. CST_IV_b and CST_IV_c are all over the place. This is further confirmed by the statistical analysis of the betadispertion wich clearly show that CST IVa and CST IVb are significantly more dispersed than the other CSTs, with CST I and CST II being the tightest clusters
### 1.4.1 - NMDS plot of vaginal samples
Figure S1: NMDS plot based on jensen-Shannon divergence, samples colored by CST and grey lines connect samples from the individual women
```{r vag_nmds,eval=T}
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}
mytheme <- theme(axis.title = element_text(size = 15), axis.text = element_text(size = 10)) + theme_bw()
load('./phyX_cst.RData')
load('./OrdinationRes.RData')
df <- data.frame(method = 'jsd', sample_data(vagX),vag.all.jsd.nmds$points)
# PCoA with CST 1 vs 2
g1 <- ggplot(data = df, aes(MDS1,MDS2, color = CST,group= dyadnb)) +
stat_ellipse(aes(group = CST)) +
geom_line(color = 'grey90') +
geom_point() +
scale_color_brewer(palette = 'Set1') +
theme(legend.position = 'none')
# PCoA with CST 3 vs 4
g2 <- ggplot(data = df, aes(MDS3,MDS4, color = CST,group= dyadnb)) +
stat_ellipse(aes(group = CST)) +
geom_line(color = 'grey90') +
geom_point() +
scale_color_brewer(palette = 'Set1') +
theme(legend.position = 'bottom')
legend <- g_legend(g2)
G1 <- ggdraw() + draw_plot(g1 + mytheme + theme(legend.position = "hidden"), 0, 0.1, 0.5, 0.9) +
draw_plot(g2 + mytheme+ theme(legend.position = "hidden"), 0.5, 0.1, 0.5, 0.9)+
draw_grob(legend, 0, 0, 1, .1)
print(G1)
pdf('FigureS1.pdf', width = 10, height = 5)
print(G1)
dev.off()
# clean environment
rm(list = ls(all = TRUE))
```
### 1.4.2 - Statistical test of beta diversity
Betadisper test differences in dispersion of each cluster, while PERMANOVA test how much of the overall differences can be explained by the variables
```{r vag_beta_stats, eval=T}
load('./OrdinationRes.RData')
load(file = "./phyX_cst.RData")
df <- data.frame(sample_data(vagX))
# Beta diversity dispersion
jsd.disp <- betadisper(vag.jsd, df$CST)
anova(jsd.disp)
TukeyHSD(jsd.disp)
boxplot(jsd.disp)
# PERMANOVA
print("PERMANOVA of Time point using Jensen-Shannon divergence")
adonis(vag.jsd ~ Time, data = df)
print("PERMANOVA of CST using Jensen-Shannon divergence")
adonis(vag.jsd ~ CST, data = df)
# clean environment
rm(list = ls(all = TRUE))
```
# 2 - Infant Samples
## 2.1 - Delivery mode
```{r infant_delivery,eval=T}
load(file = "./phyX_cst.RData")
infant <- sample_data(phyX) %>%
data.frame() %>%
filter(Type != "V") %>%
filter(!duplicated(dyadnb))
rbind(table(infant$DELIVERY) ,
100*table(infant$DELIVERY) / dim(infant)[1])
# clean environment
rm(list = ls(all = TRUE))
```
## 2.2 - Airway microbiome
### 2.2.1 - Subset airway samples
```{r air_prep,eval=FALSE}
load(file = "./phyX_cst.RData")
# subset airway samples
# ASV level
airX.raw <- subset_samples(phyX, Type == "T")
airX <- prune_taxa(taxa_sums(airX.raw) > 0, airX.raw)
airX.r <- rarefy_even_depth(airX, 2000, rngseed = 2)
airX.ra <- transform_sample_counts(airX, function(x) x/sum(x))
#Phylum level
airXphy <- tax_glom(airX, "Phylum")
taxa_names(airXphy) <- tax_table(airXphy)[,2]
airXphy.ra <- transform_sample_counts(airXphy, function(x) x/sum(x))
# Genus level
airXgenus <- tax_glom(airX,'Genus_simple')
taxa_names(airXgenus) <- tax_table(airXgenus)[,6]
airXgenus.ra <- transform_sample_counts(airXgenus, function(x) x/sum(x))
save(file = './air_taxglm.RData',list = c('airX','airXphy','airXgenus', 'airX.r','airXphy.ra','airXgenus.ra', 'airX.ra'))
# clean environment
rm(list = ls(all = TRUE))
```
**air_taxglm.RData** contains phyloseq objects with airway samples at phylum, genus and ASV level for both read counts and relative abundances, as well as a rarefied (2000 reads/sample) at ASV level.
### 2.2.2 - Dominant airway taxa and overall richness
The distribution of the airway reads are here summarized on phylum, genus and individual ASV level.
```{r air_taxa,eval=TRUE}
load('./air_taxglm.RData')
df2 <- data.frame(tax_table(airXphy), taxprc = 100*taxa_sums(airXphy.ra)/length(sample_names(airXphy.ra)))
df3 <- data.frame(tax_table(airXgenus),taxprc = 100*taxa_sums(airXgenus.ra)/length(sample_names(airXgenus.ra)))
df3$Genus <- df3$Genus_simple
df4 <- data.frame(tax_table(airX),taxprc = 100*taxa_sums(airX.ra)/length(sample_names(airX.ra)))
df.count <- data.frame(Included = c("All", "> 0.01%", "> 0.1%","> 1%"),
Phylum = c(nrow(df2),sum(df2$taxprc > 0.01),sum(df2$taxprc > 0.1),sum(df2$taxprc > 1)),
Genus = c(nrow(df3),sum(df3$taxprc > 0.01),sum(df3$taxprc > 0.1),sum(df3$taxprc > 1)),
ASV = c(nrow(df4),sum(df4$taxprc > 0.01),sum(df4$taxprc > 0.1),sum(df4$taxprc > 1)))
# Count of ASV and species in airway samples
kable(df.count, row.names = F,digits = 1, caption = 'Abundance of phyla, genera, and ASV in airway samples')
# Top 3 dominating phyla"
kable(head(df2[order(df2$taxprc,decreasing = T),]), row.names = F,digits = 1, caption = 'Abundance according to phylym')
# Top 5 dominating genus"
kable(head(df3[order(df3$taxprc,decreasing = T),]), row.names = F,digits = 1, caption = 'Abundance according to genus')
# Top 5 dominating ASV"
kable(head(df4[order(df4$taxprc,decreasing = T),]), row.names = F,digits = 1, caption = 'Abundance according to ASV')
# clean environment
rm(list = ls(all = TRUE))
```
### 2.2.3 - Airway alpha diversity
For this part we use the rarefied samples (2000 reads/sample)
```{r air_alpha,eval=TRUE}
load('./air_taxglm.RData')
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}
mytheme <- theme(axis.title = element_text(size = 15), axis.text = element_text(size = 10)) + theme_bw()
# test of alpha diversity by CST and time
df.adiv <- cbind(data.frame(sample_data(airX.r)), estimate_richness(airX.r,measures = c("Observed","Shannon")))
levels(df.adiv$Time) <- list(One.week = "1w", One.month = "1m", Three.months = "3m")
df.adiv.summary <- df.adiv %>%
group_by(Time,DELIVERY) %>%
summarise(n = n(), Observed_mean = mean(Observed), Observed_sd = sd(Observed), Shannon_mean = mean(Shannon), Shannon_sd = sd(Shannon))
df.adiv.t <- df.adiv %>%
group_by(Time) %>%
summarise(n = n(), Observed_mean = mean(Observed), Observed_sd = sd(Observed), Shannon_mean = mean(Shannon), Shannon_sd = sd(Shannon))
kable(df.adiv.t, row.names = F,digits = 3, caption = 'Summary of alpha diversity by time')
kable(df.adiv.summary, row.names = F,digits = 3, caption = 'Summary of alpha diversity by time and delivery')
# Create plot
g1 <- ggplot(df.adiv, aes(x = Time, y = Observed, fill = DELIVERY)) + geom_boxplot()+ coord_cartesian(ylim = c(0,50)) + ylab("Observed richness")
g2 <- ggplot(df.adiv, aes(x = Time, y = Shannon, fill = DELIVERY)) +
geom_boxplot() +
ylab("Shannon diversity index")+
theme(legend.position = 'bottom')
legend <- g_legend(g2)
G1 <- ggdraw() + draw_plot(g1 + mytheme + theme(legend.position = "hidden"), 0, 0.1, 0.5, 0.9) +
draw_plot(g2 + mytheme+ theme(legend.position = "hidden"), 0.5, 0.1, 0.5, 0.9)+
draw_grob(legend, 0, 0, 1, .1)
print(G1)
# Statistical testing
print("Statistical test of alpha diversity by Time and Delivery method")
fit <- aov(Observed ~ Time+DELIVERY, data = df.adiv)
anova(fit)
TukeyHSD(fit)
fit <- aov(Shannon ~ Time+DELIVERY, data = df.adiv)
anova(fit)
TukeyHSD(fit)
print("Alpha diversity does not differ dependent on mothers vaginal CST at week 36")
fit <- aov(Observed ~ Time+CST_w36, data = df.adiv)
anova(fit)
fit <- aov(Shannon ~ Time+CST_w36, data = df.adiv)
anova(fit)
# clean environment
rm(list = ls(all = TRUE))
```
### 2.2.4 - Airway beta diversity
#### 2.2.4.1 - Preparation
Calculation of Weighted UniFrac distances and NMDS ordination for airway samples
Output of this section in './air_OrdinationRes.RData'
```{r air_beta_calc,eval=FALSE}
load('./air_taxglm.RData')
cl <- parallel::makeCluster(4)
doParallel::registerDoParallel(cl)
air.WUnifrac <- UniFrac(airX, weighted=TRUE, parallel = TRUE)
air.all.nmds <- metaMDS(air.WUnifrac, k = 4, trymax = 100)
save(file = './air_OrdinationRes.RData',list = c('air.WUnifrac','air.all.nmds'))
# clean environment
rm(list = ls(all = TRUE))
```
**air_OrdinationRes.RData** contains weighted UniFrac distances and NMDS ordination of the airway samples
#### 2.2.4.2 - Plots and statistics
```{r air_beta_plot_stat,eval=T}
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}
mytheme <- theme(axis.title = element_text(size = 15), axis.text = element_text(size = 10)) + theme_bw()
load('./air_taxglm.RData')
load('./air_OrdinationRes.RData')