-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShinyStats.R
5001 lines (4318 loc) · 181 KB
/
ShinyStats.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
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
load_data_new <- function (otu.file, map.file, tree.file=NULL, parseFunction=parse_taxonomy_greengenes, version='Old',
species=TRUE, filter.no=1, rep.seq=NULL,
rff=FALSE, dep=NULL,
norm='TSS', level='OTU', intersect.no=4,
winsor=FALSE, winsor.qt=0.97,
ko.file=NULL, cog.file=NULL, ko.ann.file=NULL,
meta.sep='\t', quote="\"", comment="",
read.gg=FALSE, seed=1234, ...) {
# ko and cog file are not rarefied
# filter.no: filter the OTUs with read support less than filter.no (default is filtering singleton); singleton will not be filtered after rarefaction
# winsorization and GMPR should be further studied. Current default is false and GMPR is on the genus level
act.seq <- NULL
set.seed(seed)
meta.dat <- as.tibble(fread("maptest.txt"))
# Load Tree
tree.12 <- NULL
if (!is.null(tree.file)) {
tree.12 <- read.tree(tree.file)
if (is.rooted(tree.12) == F) {
tree.12 <- midpoint(tree.12)
}
}
filter.no = 1
biom <- read_biom(otu.file)
otu.tab <- as(biom_data(biom), "matrix")
otu.name <- observation_metadata(biom)
otu.ind <- rowSums(otu.tab) > filter.no # change otu.tab.12 != 0, rev:2016-06-20
otu.tab <- otu.tab[otu.ind, ]
# OTU names
names(otu.name) <- c('Kingdom', 'Phylum', 'Class', 'Order', 'Family', 'Genus', 'Species')
otu.name.full <- as.matrix(otu.name[, c('Kingdom', 'Phylum', 'Class', 'Order', 'Family', 'Genus', 'Species')])
otu.name.full <- otu.name.full[otu.ind, ]
if (rff == TRUE) {
cat('Rarefaction ...\n')
if (is.null(dep)) {
otu.tab.12 <- t(Rarefy(t(otu.tab.12))$otu.tab.rff)
} else {
otu.tab.12 <- t(Rarefy(t(otu.tab.12), dep)$otu.tab.rff)
}
dep <- colSums(otu.tab.12)[1]
cat("Depth ", dep, '\n')
# Remove empty OTUs
otu.ind <- rowSums(otu.tab.12) > 0 # rev:2016-06-28
otu.tab.12 <- otu.tab.12[otu.ind, ]
otu.name.12 <- otu.name.12[otu.ind, ]
otu.name.full <- otu.name.full[otu.ind, ]
act.seq <- paste0(act.seq, 'R')
} else {
rff <- FALSE
dep <- NULL
}
# Load mapping file
if (load.map == TRUE) {
samIDs <- intersect(rownames(meta.dat), colnames(otu.tab.12))
if (length(samIDs) == 0) {
stop('Sample names in the meta file and biom are completely different?\n')
}
if (length(samIDs) < length(colnames(otu.tab.12)) | length(samIDs) < length(rownames(meta.dat))) {
warning('Sample names in the meta file and biom differ! May be due to rarefaction?\n')
}
meta.dat <- meta.dat[samIDs, ]
otu.tab.12 <- otu.tab.12[, samIDs]
} else {
samIDs <- colnames(otu.tab.12)
}
# Create abundance list
cat("Create taxa abundance list ...\n")
abund.list.12 <- list()
hierachs <- c('Phylum', 'Class', 'Order', 'Family', 'Genus')
for (hierach in hierachs) {
if (hierach != 'Phylum') {
single.names <- otu.name.12[, hierach]
tax.family <- paste(otu.name.12[, 'Phylum'], single.names, sep=";")
tax.family[grepl('unclassified', tax.family, ignore.case=T)] <- paste0('Unclassified_', hierach)
} else {
tax.family <- otu.name.12[, 'Phylum']
tax.family[grepl('unclassified', tax.family, ignore.case=T)] <- 'Unclassified_Phylum'
}
family <- aggregate(otu.tab.12, by=list(tax.family), FUN=sum)
rownames(family) <- family[, 1]
family <- as.matrix(family[, -1])
abund.list.12[[hierach]] <- family
}
if (species) {
abund.list.12[['Species']] <- otu.tab.12
rownames(abund.list.12[['Species']]) <- paste0("OTU", rownames(otu.tab.12), ":", otu.name.12[, 'Phylum'], ";", otu.name.12[, 'Genus'])
}
cat('Normalize (size factor) ...\n')
if (rff == TRUE) {
cat('For rarefied data, the size factor for samples can still be different!\n')
}
if (level == 'OTU') {
data <- otu.tab.12
} else {
if (level %in% names(abund.list.12)) {
data <- abund.list.12[[level]]
} else {
data <- otu.tab.12
level <-'OTU'
warning('No or wrong level specified! OTU level will be used!\n')
}
}
# Rarefaction/Normalizing factors are not calculated for functional data
# Rev: 2017_01_19 the sample IDs for functional data are not ordered! Potential Danger! augment with NA
if (!is.null(ko.file)) {
cat("Load kegg file...\n")
ko <- read_biom(ko.file)
ko.dat <- as.matrix(biom_data(ko))
if (sum(!(samIDs %in% colnames(ko.dat))) != 0) {
missingIDs <- setdiff(samIDs, colnames(ko.dat))
aug.mat <- matrix(NA, nrow(ko.dat), length(missingIDs))
colnames(aug.mat) <- missingIDs
rownames(aug.mat) <- rownames(ko.dat)
ko.dat <- cbind(ko.dat, aug.mat)
}
ko.dat <- ko.dat[, samIDs]
# Rarefaction?
if (is.null(ko.ann.file)) {
# Old - back compatability
ko.ann <- observation_metadata(ko)
ko.ann <- cbind(KEGG_Pathways1=sapply(ko.ann, function(x) x['KEGG_Pathways1']),
KEGG_Pathways2=sapply(ko.ann, function(x) x['KEGG_Pathways2']),
KEGG_Pathways3=sapply(ko.ann, function(x) x['KEGG_Pathways3']))
rownames(ko.ann) <- rownames(ko.dat)
ko.ann[is.na(ko.ann)] <- 'Unclassified'
hierachs <- c("KEGG_Pathways1", "KEGG_Pathways2", "KEGG_Pathways3")
for (hierach in hierachs) {
tax.family <- ko.ann[, hierach]
family <- aggregate(ko.dat, by=list(tax.family), FUN=sum)
rownames(family) <- family[, 1]
family <- as.matrix(family[, -1])
abund.list.12[[hierach]] <- family
}
} else {
# New
load(ko.ann.file)
#
kos <- rownames(ko.dat)
abund.list.12[["KEGG_Pathways3"]] <- NULL
kos.id <- NULL
for (ko.item in names(kegg.map)) {
kos.common <- intersect(kos, kegg.map[[ko.item]])
if (length(kos.common) != 0) {
abund.list.12[["KEGG_Pathways3"]] <- rbind(abund.list.12[["KEGG_Pathways3"]], colSums(ko.dat[kos.common, , drop=F]))
kos.id <- c(kos.id, ko.item)
}
}
rownames(abund.list.12[["KEGG_Pathways3"]]) <- kos.id
abund.list.12[["KEGG_Metabolism"]] <- abund.list.12[["KEGG_Pathways3"]][intersect(kos.id, unlist(kegg.ann[['Metabolism']])), ]
rownames(abund.list.12[["KEGG_Metabolism"]]) <- paste0('M', rownames(abund.list.12[["KEGG_Metabolism"]]))
abund.list.12[["KEGG_Defense"]] <- NULL
kos.id <- NULL
for (ko.item in names(defense.map)) {
kos.common <- intersect(kos, defense.map[[ko.item]])
if (length(kos.common) != 0) {
abund.list.12[["KEGG_Defense"]] <- rbind(abund.list.12[["KEGG_Defense"]], colSums(ko.dat[kos.common, , drop=F]))
kos.id <- c(kos.id, ko.item)
}
}
rownames(abund.list.12[["KEGG_Defense"]]) <- kos.id
abund.list.12[["KEGG_Toxin"]] <- NULL
kos.id <- NULL
for (ko.item in names(toxin.map)) {
kos.common <- intersect(kos, toxin.map[[ko.item]])
if (length(kos.common) != 0) {
abund.list.12[["KEGG_Toxin"]] <- rbind(abund.list.12[["KEGG_Toxin"]], colSums(ko.dat[kos.common, , drop=F]))
kos.id <- c(kos.id, ko.item)
}
}
rownames(abund.list.12[["KEGG_Toxin"]]) <- kos.id
}
}
if (!is.null(cog.file)) {
cat("Load cog file...\n")
cog <- read_biom(cog.file)
cog.dat <- as.matrix(biom_data(cog))
if (sum(!(samIDs %in% colnames(cog.dat ))) != 0) {
missingIDs <- setdiff(samIDs, colnames(cog.dat ))
aug.mat <- matrix(NA, nrow(cog.dat), length(missingIDs))
colnames(aug.mat) <- missingIDs
rownames(aug.mat) <- rownames(cog.dat)
cog.dat <- cbind(cog.dat, aug.mat)
}
cog.dat <- cog.dat[, samIDs]
# rarefaction?
cog.ann <- observation_metadata(cog)
hierachs <- c("COG_Category1", "COG_Category2")
for (hierach in hierachs) {
tax.family <- sapply(cog.ann, function(x) x[hierach])
family <- aggregate(cog.dat, by=list(tax.family), FUN=sum)
rownames(family) <- family[, 1]
family <- as.matrix(family[, -1])
abund.list.12[[hierach]] <- family
}
}
# Drop tree tips
if (!is.null(tree.12)) {
absent <- tree.12$tip.label[!(tree.12$tip.label %in% rownames(otu.tab.12))]
if (length(absent) != 0) {
tree.12 <- drop.tip(tree.12, absent)
warning("The tree has OTUs not in the OTU table!")
}
}
data.obj <- list(otu.tab=otu.tab.12, abund.list=abund.list.12, meta.dat=meta.dat, tree=tree.12,
otu.name=otu.name.12, otu.name.full=otu.name.full,
size.factor=sf, norm.method=norm, norm.level=level,
winsor=winsor, winsor.qt=winsor.qt,
rff=rff, rff.dep=dep, act.seq=act.seq,
call=match.call())
data.obj <- list(otu.tab=otu.tab,otu.name=otu.name,otu.name.full=otu.name.full, tree=tree.12)
}
# Rev: 2016_09_22 Add load.map
# Rev: 2016_12_12 Reogranize rarefy, normalize, winsorize
load_data <- function (otu.file, map.file, tree.file=NULL, load.map=TRUE, parseFunction=parse_taxonomy_default, version='Old',
species=TRUE, filter.no=1, rep.seq=NULL,
rff=FALSE, dep=NULL,
norm='TSS', level='OTU', intersect.no=4,
winsor=FALSE, winsor.qt=0.97,
ko.file=NULL, cog.file=NULL, ko.ann.file=NULL,
meta.sep='\t', quote="\"", comment="",
read.gg=FALSE, seed=1234, ...) {
# ko and cog file are not rarefied
# filter.no: filter the OTUs with read support less than filter.no (default is filtering singleton); singleton will not be filtered after rarefaction
# winsorization and GMPR should be further studied. Current default is false and GMPR is on the genus level
act.seq <- NULL
set.seed(seed)
if (load.map == TRUE) {
cat("Load meta file...\n")
if (grepl("csv$", map.file)) {
meta.dat <- read.csv(map.file, header=T, check.names=F, row.names=1, comment=comment, quote=quote, ...)
} else {
meta.dat <- read.table(map.file, header=T, check.names=F, row.names=1, comment=comment, sep=meta.sep, quote=quote, ...)
}
} else {
meta.dat <- NULL
}
# Load Tree
if (!is.null(tree.file)) {
cat("Load tree file ...\n")
if (read.gg == F) {
tree.12 <- read.tree(tree.file)
} else {
tree.12 <- read_tree_greengenes(tree.file)
}
if (is.rooted(tree.12) == F) {
tree.12 <- midpoint(tree.12)
}
} else {
tree.12 <- NULL
}
cat("Load OTU file...\n") # Rewrite load new biom file, rev:2016-06-20
if (version != 'New') {
biom.obj <- import_biom(otu.file, parseFunction = parseFunction)
colnames(tax_table(biom.obj)) <- c('Kingdom', 'Phylum', 'Class', 'Order', 'Family', 'Genus', 'Species')
otu.tab.12 <- otu_table(biom.obj)@.Data
otu.ind <- rowSums(otu.tab.12) > filter.no # change otu.tab.12 != 0, rev:2016-06-20
otu.tab.12 <- otu.tab.12[otu.ind, ]
# OTU names
otu.name.full <- as.matrix(biom.obj@tax_table[, c('Kingdom', 'Phylum', 'Class', 'Order', 'Family', 'Genus', 'Species')])
otu.name.full <- otu.name.full[otu.ind, ]
otu.name.12 <- otu.name.full[, c('Kingdom', 'Phylum', 'Class', 'Order', 'Family', 'Genus', 'Species')]
otu.name.12[is.na(otu.name.12)] <- 'unclassified'
otu.name.12 <- otu.name.12@.Data
otu.name.12[, ] <- gsub('\\[', '', otu.name.12)
otu.name.12[, ] <- gsub('\\]', '', otu.name.12)
otu.name.full <- otu.name.full@.Data
} else {
temp <- read_hdf5_biom(otu.file)
otu.tab.12 <- matrix(unlist(temp$data), byrow=T, nrow=temp$shape[1], ncol=temp$shape[2])
otu.ids <- sapply(temp$rows, function(x) x[['id']])
sam.ids <- sapply(temp$columns, function(x) x[['id']])
# From phyloseq: to be double checked!! Checked!
if (all(sapply(sapply(temp$rows, function(i) {
i$metadata
}), is.null))) {
otu.name.full <- NULL
} else {
taxlist = lapply(temp$rows, function(i) {
parseFunction(i$metadata$taxonomy)
})
names(taxlist) = sapply(temp$rows, function(i) {
i$id
})
otu.name.full = build_tax_table(taxlist)
}
otu.name.full <- otu.name.full@.Data
rownames(otu.tab.12) <- otu.ids
colnames(otu.tab.12) <- sam.ids
otu.ind <- rowSums(otu.tab.12) > filter.no # change otu.tab.12 != 0, rev:2016-06-20
otu.tab.12 <- otu.tab.12[otu.ind, ]
otu.name.full <- otu.name.full[otu.ind, ]
otu.name.12 <- otu.name.full[, c('Kingdom', 'Phylum', 'Class', 'Order', 'Family', 'Genus', 'Species')]
otu.name.12[is.na(otu.name.12)] <- 'unclassified'
otu.name.12[, ] <- gsub('\\[', '', otu.name.12)
otu.name.12[, ] <- gsub('\\]', '', otu.name.12)
}
if (rff == TRUE) {
cat('Rarefaction ...\n')
if (is.null(dep)) {
otu.tab.12 <- t(Rarefy(t(otu.tab.12))$otu.tab.rff)
} else {
otu.tab.12 <- t(Rarefy(t(otu.tab.12), dep)$otu.tab.rff)
}
dep <- colSums(otu.tab.12)[1]
cat("Depth ", dep, '\n')
# Remove empty OTUs
otu.ind <- rowSums(otu.tab.12) > 0 # rev:2016-06-28
otu.tab.12 <- otu.tab.12[otu.ind, ]
otu.name.12 <- otu.name.12[otu.ind, ]
otu.name.full <- otu.name.full[otu.ind, ]
act.seq <- paste0(act.seq, 'R')
} else {
rff <- FALSE
dep <- NULL
}
# Load mapping file
if (load.map == TRUE) {
samIDs <- intersect(rownames(meta.dat), colnames(otu.tab.12))
if (length(samIDs) == 0) {
stop('Sample names in the meta file and biom are completely different?\n')
}
if (length(samIDs) < length(colnames(otu.tab.12)) | length(samIDs) < length(rownames(meta.dat))) {
warning('Sample names in the meta file and biom differ! May be due to rarefaction?\n')
}
meta.dat <- meta.dat[samIDs, ]
otu.tab.12 <- otu.tab.12[, samIDs]
} else {
samIDs <- colnames(otu.tab.12)
}
# Create abundance list
cat("Create taxa abundance list ...\n")
abund.list.12 <- list()
hierachs <- c('Phylum', 'Class', 'Order', 'Family', 'Genus')
for (hierach in hierachs) {
if (hierach != 'Phylum') {
single.names <- otu.name.12[, hierach]
tax.family <- paste(otu.name.12[, 'Phylum'], single.names, sep=";")
tax.family[grepl('unclassified', tax.family, ignore.case=T)] <- paste0('Unclassified_', hierach)
} else {
tax.family <- otu.name.12[, 'Phylum']
tax.family[grepl('unclassified', tax.family, ignore.case=T)] <- 'Unclassified_Phylum'
}
family <- aggregate(otu.tab.12, by=list(tax.family), FUN=sum)
rownames(family) <- family[, 1]
family <- as.matrix(family[, -1])
abund.list.12[[hierach]] <- family
}
if (species) {
abund.list.12[['Species']] <- otu.tab.12
rownames(abund.list.12[['Species']]) <- paste0("OTU", rownames(otu.tab.12), ":", otu.name.12[, 'Phylum'], ";", otu.name.12[, 'Genus'])
}
cat('Normalize (size factor) ...\n')
if (rff == TRUE) {
cat('For rarefied data, the size factor for samples can still be different!\n')
}
if (level == 'OTU') {
data <- otu.tab.12
} else {
if (level %in% names(abund.list.12)) {
data <- abund.list.12[[level]]
} else {
data <- otu.tab.12
level <-'OTU'
warning('No or wrong level specified! OTU level will be used!\n')
}
}
if (norm == 'GMPR') {
sf <- GMPR(data, intersect.no=intersect.no)
warning('GMPR is only suitable for samples from the same body location!\n')
norm <- 'GMPR'
names(sf) <- colnames(data)
act.seq <- paste0(act.seq, 'N')
} else {
if (norm == 'TSS') {
sf <- colSums(data)
norm <- 'TSS'
act.seq <- paste0(act.seq, 'N')
} else {
warning('Normalization method not specified or unknown! TSS is used!\n')
sf <- colSums(data)
norm <- 'TSS'
act.seq <- paste0(act.seq, 'N')
}
}
if (winsor == TRUE) {
act.seq <- paste0(act.seq, 'W')
if (rff == TRUE) {
warning('Winsorization after rarefaction will make the data have different total numbers!\n')
}
cat('Winsorize ...\n')
if (is.null(winsor.qt)) {
winsor.qt <- 0.97
}
# Addressing the outlier (97% percent) or at least one outlier
abund.list.12 <- sapply(abund.list.12, function(genus) {
genus.p <- t(t(genus) / sf)
genus.p <- apply(genus.p, 1, function(x) {
cutoff <- quantile(x, winsor.qt)
x[x >= cutoff] <- cutoff
x
}
)
# column/row switch
genus.w <- t(round(genus.p * sf))
})
# OTU table
otu.tab.12.p <- t(t(otu.tab.12) / sf)
otu.tab.12.p <- apply(otu.tab.12.p, 1, function(x) {
cutoff <- quantile(x, winsor.qt)
x[x >= cutoff] <- cutoff
x
}
)
# column/row switch
otu.tab.12 <- t(round(otu.tab.12.p * sf))
} else {
winsor <- FALSE
winsor.qt <- NULL
}
# Rarefaction/Normalizing factors are not calculated for functional data
# Rev: 2017_01_19 the sample IDs for functional data are not ordered! Potential Danger! augment with NA
if (!is.null(ko.file)) {
cat("Load kegg file...\n")
ko <- read_biom(ko.file)
ko.dat <- as.matrix(biom_data(ko))
if (sum(!(samIDs %in% colnames(ko.dat))) != 0) {
missingIDs <- setdiff(samIDs, colnames(ko.dat))
aug.mat <- matrix(NA, nrow(ko.dat), length(missingIDs))
colnames(aug.mat) <- missingIDs
rownames(aug.mat) <- rownames(ko.dat)
ko.dat <- cbind(ko.dat, aug.mat)
}
ko.dat <- ko.dat[, samIDs]
# Rarefaction?
if (is.null(ko.ann.file)) {
# Old - back compatability
ko.ann <- observation_metadata(ko)
ko.ann <- cbind(KEGG_Pathways1=sapply(ko.ann, function(x) x['KEGG_Pathways1']),
KEGG_Pathways2=sapply(ko.ann, function(x) x['KEGG_Pathways2']),
KEGG_Pathways3=sapply(ko.ann, function(x) x['KEGG_Pathways3']))
rownames(ko.ann) <- rownames(ko.dat)
ko.ann[is.na(ko.ann)] <- 'Unclassified'
hierachs <- c("KEGG_Pathways1", "KEGG_Pathways2", "KEGG_Pathways3")
for (hierach in hierachs) {
tax.family <- ko.ann[, hierach]
family <- aggregate(ko.dat, by=list(tax.family), FUN=sum)
rownames(family) <- family[, 1]
family <- as.matrix(family[, -1])
abund.list.12[[hierach]] <- family
}
} else {
# New
load(ko.ann.file)
#
kos <- rownames(ko.dat)
abund.list.12[["KEGG_Pathways3"]] <- NULL
kos.id <- NULL
for (ko.item in names(kegg.map)) {
kos.common <- intersect(kos, kegg.map[[ko.item]])
if (length(kos.common) != 0) {
abund.list.12[["KEGG_Pathways3"]] <- rbind(abund.list.12[["KEGG_Pathways3"]], colSums(ko.dat[kos.common, , drop=F]))
kos.id <- c(kos.id, ko.item)
}
}
rownames(abund.list.12[["KEGG_Pathways3"]]) <- kos.id
abund.list.12[["KEGG_Metabolism"]] <- abund.list.12[["KEGG_Pathways3"]][intersect(kos.id, unlist(kegg.ann[['Metabolism']])), ]
rownames(abund.list.12[["KEGG_Metabolism"]]) <- paste0('M', rownames(abund.list.12[["KEGG_Metabolism"]]))
abund.list.12[["KEGG_Defense"]] <- NULL
kos.id <- NULL
for (ko.item in names(defense.map)) {
kos.common <- intersect(kos, defense.map[[ko.item]])
if (length(kos.common) != 0) {
abund.list.12[["KEGG_Defense"]] <- rbind(abund.list.12[["KEGG_Defense"]], colSums(ko.dat[kos.common, , drop=F]))
kos.id <- c(kos.id, ko.item)
}
}
rownames(abund.list.12[["KEGG_Defense"]]) <- kos.id
abund.list.12[["KEGG_Toxin"]] <- NULL
kos.id <- NULL
for (ko.item in names(toxin.map)) {
kos.common <- intersect(kos, toxin.map[[ko.item]])
if (length(kos.common) != 0) {
abund.list.12[["KEGG_Toxin"]] <- rbind(abund.list.12[["KEGG_Toxin"]], colSums(ko.dat[kos.common, , drop=F]))
kos.id <- c(kos.id, ko.item)
}
}
rownames(abund.list.12[["KEGG_Toxin"]]) <- kos.id
}
}
if (!is.null(cog.file)) {
cat("Load cog file...\n")
cog <- read_biom(cog.file)
cog.dat <- as.matrix(biom_data(cog))
if (sum(!(samIDs %in% colnames(cog.dat ))) != 0) {
missingIDs <- setdiff(samIDs, colnames(cog.dat ))
aug.mat <- matrix(NA, nrow(cog.dat), length(missingIDs))
colnames(aug.mat) <- missingIDs
rownames(aug.mat) <- rownames(cog.dat)
cog.dat <- cbind(cog.dat, aug.mat)
}
cog.dat <- cog.dat[, samIDs]
# rarefaction?
cog.ann <- observation_metadata(cog)
hierachs <- c("COG_Category1", "COG_Category2")
for (hierach in hierachs) {
tax.family <- sapply(cog.ann, function(x) x[hierach])
family <- aggregate(cog.dat, by=list(tax.family), FUN=sum)
rownames(family) <- family[, 1]
family <- as.matrix(family[, -1])
abund.list.12[[hierach]] <- family
}
}
# Drop tree tips
if (!is.null(tree.12)) {
absent <- tree.12$tip.label[!(tree.12$tip.label %in% rownames(otu.tab.12))]
if (length(absent) != 0) {
tree.12 <- drop.tip(tree.12, absent)
warning("The tree has OTUs not in the OTU table!")
}
}
data.obj <- list(otu.tab=otu.tab.12, abund.list=abund.list.12, meta.dat=meta.dat, tree=tree.12,
otu.name=otu.name.12, otu.name.full=otu.name.full,
size.factor=sf, norm.method=norm, norm.level=level,
winsor=winsor, winsor.qt=winsor.qt,
rff=rff, rff.dep=dep, act.seq=act.seq,
call=match.call())
}
# Rev: 2016_11_28, Bray-curtis use normalized data.
construct_distance <- function (data.obj, unifrac.file=NULL, Phylum='All', dist.RData=NULL, save.RData=NULL,
filter.no=0, rff=FALSE, dep=NULL, seed=1234) {
set.seed(seed)
if (!is.null(dist.RData)) {
load(dist.RData, envir=.GlobalEnv )
} else {
dist.list.12 <- list()
cat("Generalized UniFrac ...\n")
otu.tab <- t(data.obj$otu.tab)
if (rff == TRUE) {
if (is.null(dep)) {
otu.tab <- Rarefy(otu.tab)$otu.tab.rff
} else {
otu.tab <- Rarefy(otu.tab, dep)$otu.tab.rff
}
}
if (Phylum != 'All') {
ind <- data.obj$otu.name[, 'Phylum'] == Phylum
otu.tab <- otu.tab[, ind]
}
# Filter otus with reads <= filter.no
otu.tab <- otu.tab[, colSums(otu.tab) > filter.no]
# Remove samples with no reads
if (sum(rowSums(otu.tab) == 0) >= 1) {
otu.tab <- otu.tab[rowSums(otu.tab) != 0, ]
warning('Some samples do not have reads after rarefaction! Please be careful!\n')
}
# To make sure the OTUs in otu.tab are in the tree (rev:2016-06-19)
if (sum(!(colnames(otu.tab) %in% data.obj$tree$tip.label))) {
warning('Some OTU names are not in the tree! An intersection set will be used!\n')
}
common.otus <- intersect(colnames(otu.tab), data.obj$tree$tip.label)
unifrac12 <- GUniFrac(otu.tab[, common.otus], data.obj$tree)$unifracs
dist.list.12[['WUniFrac']] <- unifrac12[, , 'd_1']
dist.list.12[['GUniFrac']] <- unifrac12[, , 'd_0.5']
if (is.null(unifrac.file)) {
dist.list.12[['UniFrac']] <- unifrac12[, , 'd_UW']
} else {
# The orders may be different
dist.list.12[['UniFrac']] <- as.matrix(read.table(unifrac.file, row.names=1, header=T)) # Rarefaction
}
# Need speed up
# Suggest using rarefied counts
# If case/control has different sequencing depth, it will result in false clustering!
# Rev: 2016_11_28 Use normalized data for BC distance calculation to reduce noise in case of variable library size
dist.list.12[['BC']] <-as.matrix(vegdist(otu.tab / rowSums(otu.tab)))
genus <- t(data.obj$abund.list[['Genus']])
genus <- genus / rowSums(genus)
dist.list.12[['Euc']] <- as.matrix(dist(genus))
genus <- sqrt(genus)
dist.list.12[['Hel']] <-as.matrix(dist(genus))
# dist.list.12[['JS']] <- as.matrix(distance(otu_table(data.obj$abund.list[['Genus']], taxa_are_rows=T), method='jsd'))
if (!is.null(save.RData)) {
save(dist.list.12, file=save.RData)
}
}
return(dist.list.12)
}
is.na.null <- function (x) {
if (is.null(x)) {
return(TRUE)
} else {
if (is.na(x)[1]) {
return(TRUE)
} else {
return(FALSE)
}
}
}
# Rev: 2016_09_26 remove empty OTUs/taxa
# Rev: 2016_12_01 add more logical controls
subset_data <- function (data.obj, samIDs) {
# Rev: 2016_1_19 to add error protection
# Transform logical samIDs into characer samIDs
if (is.logical(samIDs) | is.numeric(samIDs)) {
samIDs <- rownames(data.obj$meta.dat)[samIDs]
}
data.obj$meta.dat <- data.obj$meta.dat[samIDs, , drop=FALSE]
if (!is.na.null(data.obj$otu.tab)) {
data.obj$otu.tab <- data.obj$otu.tab[, samIDs, drop=FALSE]
data.obj$otu.tab <- data.obj$otu.tab[rowSums(data.obj$otu.tab) != 0, , drop=FALSE]
data.obj$otu.name <- data.obj$otu.name[rownames(data.obj$otu.tab), , drop=FALSE]
if (!is.na.null(data.obj$otu.name.full)) {
data.obj$otu.name.full <- data.obj$otu.name.full[rownames(data.obj$otu.tab), , drop=FALSE]
}
}
if (!is.na.null(data.obj$abund.list)) {
data.obj$abund.list <- lapply(data.obj$abund.list, function(x) {
xx <- x[, samIDs, drop=FALSE]
xx <- xx[rowSums(xx) != 0, , drop=FALSE]
})
}
if (!is.na.null(data.obj$size.factor)) {
data.obj$size.factor <- data.obj$size.factor[samIDs]
}
if (!is.na.null(data.obj$ko.list)) {
data.obj$ko.list <- lapply(data.obj$ko.list, function(x) {
xx <- x[, samIDs, drop=FALSE]
xx <- xx[rowSums(xx) != 0, , drop=FALSE]
})
}
if (!is.na.null(data.obj$cog.list)) {
data.obj$cog.list <- lapply(data.obj$cog.list, function(x) {
xx <- x[, samIDs, drop=FALSE]
xx <- xx[rowSums(xx) != 0, , drop=FALSE]
})
}
return(data.obj)
}
# Rev: 2016_12_01 add more logical controls
# Rev: 2016_02_01 fix one error
subset_dist <- function (dist.obj, samIDs) {
# Rev: 2016_1_19 to add error protection
# Transform logical samIDs into character samIDs
if (is.logical(samIDs) | is.numeric(samIDs)) {
samIDs <- rownames(dist.obj[[1]])[samIDs]
}
lapply(dist.obj, function(x) {
if(!is.na.null(x)){
x <- x[samIDs, samIDs]
} else {
x
}
x
})
}
perform_sequence_stat_analysis <- function (data.obj, ann='') {
sink(paste0('Sequence_Analysis_Statistics_', ann, '.txt'))
otu.tab <- data.obj$otu.tab
# Sequencing depth
otu.abund <- rowSums(otu.tab)
sam.abund <- colSums(otu.tab)
otu.prev <- rowSums(otu.tab!=0)/ncol(otu.tab)
otu.abund <- otu.abund[otu.abund >= 1]
sam.abund <- sam.abund[sam.abund >= 1]
cat('This data set contains ', length(sam.abund), ' samples after quality controls.\n')
cat('16S rDNA targeted sequencing yields ', mean(sam.abund), 'reads/sample on average (range:', min(sam.abund), '-', max(sam.abund), ').')
cat('Clustering of these 16S sequence tags produces ', sum(otu.abund > 0), ' OTUs at 97% similarity level.')
phy.abund <- data.obj$abund.list[['Phylum']]
fam.abund <- data.obj$abund.list[['Family']]
gen.abund <- data.obj$abund.list[['Genus']]
phy.prev <- rowSums(phy.abund != 0) / ncol(phy.abund)
fam.prev <- rowSums(fam.abund != 0) / ncol(phy.abund)
gen.prev <- rowSums(gen.abund != 0) / ncol(phy.abund)
phy.abund <- rowMeans(t(t(phy.abund) / sam.abund))
fam.abund <- rowMeans(t(t(fam.abund) / sam.abund))
gen.abund <- rowMeans(t(t(gen.abund) / sam.abund))
cat('These OTUs belong to ', sum(phy.abund > 0), ' phyla,', sum(fam.abund > 0), ' families and ', sum(gen.abund > 0), 'genera.\n\n')
phy.prev <- sort(phy.prev, decr=T)
phy.prev <- round(phy.prev[phy.prev >= 0.05] * 100, 2)
fam.prev <- sort(fam.prev, decr=T)
fam.prev <- round(fam.prev[fam.prev >= 0.05] * 100, 2)
gen.prev <- sort(gen.prev, decr=T)
gen.prev <- round(gen.prev[gen.prev >= 0.05] * 100, 2)
# Rev: 2017_02_19 ' ' -> '\n'
cat('\nThe most prevalent phyla are:\n', paste(paste0(names(phy.prev), '(', phy.prev, '%)'), collapse='\n'), '\n')
cat('\nThe most prevalent families are:\n', paste(paste0(names(fam.prev), '(', fam.prev, '%)'), collapse='\n'), '\n')
cat('\nand the most prevalent genera are:\n', paste(paste0(names(gen.prev), '(', gen.prev, '%)'), collapse='\n'), '\n\n')
phy.abund <- sort(phy.abund, decr=T)
phy.abund <- round(phy.abund[phy.abund >= 0.05] * 100, 2)
fam.abund <- sort(fam.abund, decr=T)
fam.abund <- round(fam.abund[fam.abund >= 0.05] * 100, 2)
gen.abund <- sort(gen.abund, decr=T)
gen.abund <- round(gen.abund[gen.abund >= 0.05] * 100, 2)
cat('\nThe most abundant phyla are ', paste(paste0(names(phy.abund), '(', phy.abund, '%)'), collapse=' '), ';')
cat('\nThe most abundant families are ', paste(paste0(names(fam.abund), '(', fam.abund, '%)'), collapse=' '), ';')
cat('\nand the most abundant genera are ', paste(paste0(names(gen.abund), '(', gen.abund, '%)'), collapse=' '), '.')
sink()
sink(paste0('Sequence_Analysis_Statistics_table_', ann, '.tsv'))
write.table(cbind(read.table(text=names(phy.prev)), unname(phy.prev), "Phylum", "Prevalence"), row.names=FALSE, col.names=FALSE)
write.table(cbind(read.table(text=names(fam.prev)), unname(fam.prev), "Family", "Prevalence"), row.names=FALSE, col.names=FALSE)
write.table(cbind(read.table(text=names(gen.prev)), unname(gen.prev), "Genus", "Prevalence"), row.names=FALSE, col.names=FALSE)
write.table(cbind(read.table(text=names(phy.abund)), unname(phy.abund), "Phylum", "Abundance"), row.names=FALSE, col.names=FALSE)
write.table(cbind(read.table(text=names(fam.abund)), unname(fam.abund), "Family", "Abundance"), row.names=FALSE, col.names=FALSE)
write.table(cbind(read.table(text=names(gen.abund)), unname(gen.abund), "Genus", "Abundance"), row.names=FALSE, col.names=FALSE)
sink()
png(paste0('Sequence_Analysis_Statistics_', ann, '.png'), height=600, width=900)
obj1 <- ggplot2::ggplot(data=data.frame(x=sam.abund), aes(x=x)) + geom_histogram(col='black', fill='gray') + ylab('Frequency') + xlab('Sequencing depth') + theme_bw()
otu.tab <- data.obj$otu.tab
map <- data.obj$meta.dat
colnames(otu.tab) <- map[[ann]]
df <- data.frame(Group=names(colSums(otu.tab)), coverage=colSums(otu.tab))
obj2 <- ggplot2::ggplot(df, aes(x=Group, y=log10(coverage), col=Group)) + geom_boxplot(position=position_dodge(width=0.75), outlier.colour = NA) +
geom_jitter(alpha=0.6, size=3.0, position = position_jitter(w = 0.1)) + theme_bw()
multiplot(obj1,obj2, cols=1)
dev.off()
sink(paste0('Sequence_Analysis_Statistics_log10Coverage_Association_', ann, '.tsv'))
map$log10_coverage <- log10(colSums(data.obj$otu.tab))
lm.obj <- lm(as.formula(paste('log10_coverage ~ ', ann)), map)
prmatrix(summary(lm.obj)$coefficients)
sink()
}
# Rev: 2017_08_23 add automatically create phylo.obj
generate_rarefy_curve <- function (data.obj, phylo.obj=NULL, grp.name, depth=NULL, npoint=10, iter.no=5,
measures=c('Observed', 'Chao1', 'Shannon', 'InvSimpson'), ann='', gg.cmd="theme(legend.justification=c(1,0), legend.position=c(1,0))", wid=5, hei=5) {
cat("Create rarefaction curves!\n")
# Rev: 2017_08_23
if (is.null(phylo.obj)) {
phylo.obj <- phyloseq(otu_table(data.obj$otu.tab, taxa_are_rows=T), phy_tree(data.obj$tree),
tax_table(data.obj$otu.name), sample_data(data.obj$meta.dat))
}
if (is.null(depth)) {
depth <- min(sample_sums(phylo.obj))
phylo.even <- rarefy_even_depth(phylo.obj, rngseed=12345)
} else {
if (depth > min(sample_sums(phylo.obj))) {
ind <- sample_sums(phylo.obj) >= depth
cat(sum(!ind), " samples do not have sufficient number of reads!\n")
sample_data(phylo.obj) <- sample_data(phylo.obj)[ind, ]
data.obj <- subset_data(data.obj, ind)
}
phylo.even <- rarefy_even_depth(phylo.obj, depth, rngseed=12345)
}
df <- data.obj$meta.dat
grp <- df[, grp.name]
# Rev: 2016_12_12
if (is.character(grp)) {
grp <- factor(grp)
}
if (!is.factor(grp)) {
stop('Rarefaction curve needs a factor!\n')
}
res <- NULL
incr <- depth %/% npoint
sink('temp.txt')
for (dep in c(10, incr*(1:npoint))) {
x <- 0
for (i in 1:iter.no) {
phylo.even <- rarefy_even_depth(phylo.obj, dep, rngseed=12345+i)
x <- x + estimate_richness(phylo.even, measures=measures)
}
res <- rbind(res, t(x[, measures, drop=F]/iter.no))
}
colnames(res) <- rownames(df)
sink()
res_list <- list()
for (i in 1:length(measures)) {
measure <- measures[i]
cat("Measure: ", measure, "\n")
res2 <- res[(0:(npoint))*length(measures)+i, , drop=F]
m <- t(apply(res2, 1, function(x) tapply(x, grp, mean)))
se <- t(apply(res2, 1, function(x) tapply(x, grp, function(y) sd(y)/sqrt(length(y)))))
uci <- m+se
lci <- m-se
m <- melt(m)
uci <- melt(uci)
lci <- melt(lci)
res2 <- cbind(c(10, incr*(1:npoint)), m[, 2:3], uci[, 3], lci[, 3])
colnames(res2) <- c('Depth', 'Group', 'mean', 'max', 'min')
res2 <- as.data.frame(res2)
res2$Group <- factor(res2$Group, levels=levels(grp))
res_list[[measure]] <- res2
res2
}
mres_list = melt(res_list, measure.vars=c("mean", "max", "min"))
cres_list <- dcast(mres_list, L1 + Group + Depth ~ variable, fun.aggregate=mean)
obj <- ggplot(cres_list, aes(x=Depth, y=mean, color=Group, group=Group)) +
geom_errorbar(aes(ymin=min, ymax=max), alpha=0.5, width=.25, position=position_dodge(.2)) +
geom_line() +
geom_point(size=3, shape=21, fill="white") +
labs(y="Alpha diversity") +
facet_wrap(~ L1, scale="free_y") + theme_bw()
return(obj)
}
# Rev: 2016_09_10
# Rev: 2016_11_28
# Rev: 2017_04_18
generate_alpha_boxplot <- function (data.obj, phylo.obj=NULL, rarefy=TRUE, depth=NULL, grp.name, strata=NULL,
measures=c('Observed', 'Chao1', 'Shannon', 'InvSimpson'), gg.cmd=NULL, ann='', subject=NULL, p.size=2.5, l.size=0.5,
hei = NULL, wid = NULL) {
# Rev: 2017_08_23
if (is.null(phylo.obj)) {
phylo.obj <- phyloseq(otu_table(data.obj$otu.tab, taxa_are_rows=T), phy_tree(data.obj$tree),
tax_table(data.obj$otu.name), sample_data(data.obj$meta.dat))
}
# To be completed - jetter when strata is not null
if (rarefy == TRUE) {
if (is.null(depth)) {
depth <- min(sample_sums(phylo.obj))
} else {
if (depth > min(sample_sums(phylo.obj))) {
ind <- (sample_sums(phylo.obj) >= depth)
cat(sum(!ind), " samples do not have sufficient number of reads!\n")
sample_data(phylo.obj) <- sample_data(phylo.obj)[ind, ]
data.obj <- subset_data(data.obj, ind)
}
}
phylo.even <- rarefy_even_depth(phylo.obj, depth, rngseed=12345)
est_rich <- estimate_richness(phylo.even, measures=measures)
} else {
est_rich <- estimate_richness(phylo.obj, measures=measures)
}
df <- data.obj$meta.dat
grp <- df[, grp.name]
obj_list <- list()
df = data.frame(Value=est_rich[, measures], Group=grp)
mdf <- melt(df, id="Group")
obj <- ggplot(mdf, aes(x=as.factor(Group), y=value, col=as.factor(Group), group=as.factor(Group))) +
geom_boxplot(position=position_dodge(width=0.75), outlier.colour = NA) +
geom_jitter(alpha=0.6, size=3.0, position = position_jitter(w = 0.1)) +
labs(y="Alpha Diversity", x="Group") +
facet_wrap(~ variable, scale="free_y") +
theme_bw()
return(obj)
}
# New: 2018_03_09 Removing phyloseq dependency and add 'subject' parameter, and remove 'model' parameter
perform_alpha_test2 <- function (data.obj, alpha.obj=NULL, rarefy=TRUE, depth=NULL, iter.no=5,
measures=c('Observed', 'Chao1', 'Shannon', 'InvSimpson'), model='lm',
formula=NULL, grp.name=NULL, adj.name=NULL, subject=NULL, ann='', seed=123, ...) {
if (is.null(alpha.obj)) {
alpha.obj <- generate_alpha_diversity(data.obj, rarefy=rarefy, depth=depth, iter.no=iter.no, measures=measures, seed=seed)
} else {
if (sum(!(rownames(alpha.obj) %in% rownames(data.obj$meta.dat))) != 0){
stop("alpha.obj contains samples not in data.obj!\n")
}
}
x <- alpha.obj
df <- data.obj$meta.dat[rownames(alpha.obj), ]
if (is.null(subject)) {
model <- 'lm'
} else {
model <- 'lme'
}
result <- list()
fitted.obj <- list()
# variables to adjust always come first in anova analyses
if (is.null(formula)) {
if (is.null(adj.name)) {
formula <- paste('~', grp.name)
} else {
formula <- paste('~', paste(adj.name, collapse='+'), '+', grp.name)
}
}