-
Notifications
You must be signed in to change notification settings - Fork 0
/
flies.analysis5.Rmd
2917 lines (1724 loc) · 103 KB
/
flies.analysis5.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: "Flies: Everything V5"
output:
html_document:
self_contained: yes
toc: yes
toc_float: no
---
```{r, include=FALSE}
#Some general options and other pre-processing steps.
## ie Types of comparisons, filtering, future options
#Compare against control or all comparisons? Comment out the one does not apply
#To control
f = as.formula("trt.vs.ctrl~Group")
#All pairwise
# f = as.formula("pairwise~Group")
```
```{r, include=FALSE}
options(repos = BiocManager::repositories())
getOption("repos")
library(ordinal)
library(knitr)
library(glmmTMB)
library(reshape2)
library(ggplot2)
library(viridis)
library(emmeans)
library(car)
library(shiny)
library(plotly)
library(patchwork)
library(powerMediation)
library(pwr)
library(dplyr)
library(data.table)
library(pwr)
library(gghalves)
library(sgpv)
library(diptest)
library(mclust)
library(sigclust)
library(LaplacesDemon)
library(viridis)
library(mousetrap)
library(lme4)
library(tidyr)
library(readxl)
library(robustlmm)
library(zoo)
library(pheatmap)
options(scipen=999)
opts_chunk$set(echo=FALSE, fig.align='center', warning=FALSE, message=FALSE, dev=c('png','cairo_pdf','tiff','jpeg'), cache=FALSE,error=FALSE,fig.width=8,fig.height=10)
substrRight <- function(x, n){
substr(x, nchar(x)-n+1, nchar(x))
}
setwd("/data/home/zachary.madaj/flies/")
library(qdapRegex)
all.files = list.files(pattern = ".xlsx$", recursive = TRUE)
```
```{r}
# Code chunk to store functions for use later on
format_heat = function(df.ht){
df.ht$Comparison = gsub(" - Control","",df.ht$Comparison)
df.ht$Amount = substrRight(df.ht$Comparison,1)
df.ht$Compound = gsub(" ","" ,substr(df.ht$Comparison ,1,nchar(df.ht$Comparison )-1))
heat.df = reshape(subset(df.ht, select = - c(Comparison)), idvar = "Compound", timevar = "Amount", direction = "wide")
rownames(heat.df) = heat.df$Compound
heat.df = subset(heat.df,select= - c(Compound))
heat.df = heat.df[,order(as.numeric(gsub(" ","",substr(colnames(heat.df),1,2))), factor(substrRight(colnames(heat.df),1),levels=c("L","M","H")))]
return(heat.df)
}
p_val_heatmap = function(heat.df){
if(ncol(heat.df)/3>=2) {
annotate = data.frame(Out = substr(colnames(heat.df),1,nchar(colnames(heat.df))-1), Amount = factor(substrRight(colnames(heat.df),1),levels=c("L","M","H")))
rownames(annotate) = colnames(heat.df)
Var1 = viridis::viridis(ncol(heat.df)/3)
names(Var1) = c(unique(annotate$Out))
Var2 = rev(viridis::mako(3))
names(Var2) = c(unique(annotate$Amount))
anno_colors = list(Out = Var1,Amount=Var2)
} else {
annotate = data.frame(Amount = factor(substrRight(colnames(heat.df),1),levels=c("L","M","H")))
rownames(annotate) = colnames(heat.df)
Var1 = rev(viridis::mako(3))
names(Var1) = c(unique(annotate$Amount))
anno_colors = list(Amount=Var1)
}
breaks = seq(0,1,0.05)
mycols = colorRampPalette(c("darkred","white","black"))(length(breaks)-2)
# print(pheatmap(heat.df, cluster_rows = F,cluster_cols = F, annotation_col = annotate, annotation_colors =anno_colors, color=mycols,breaks=breaks))
heat.df.gg = heat.df
heat.df.gg$Compound = rownames(heat.df.gg)
heat.m = reshape2::melt(heat.df.gg,id.vars=c("Compound"))
heat.m$Outcome = gsub("\\..*","",heat.m$variable)
if(all(! is.na(as.numeric(substr(heat.m$Outcome,1,1))))){
heat.m$Outcome = factor(heat.m$Outcome,levels=unique(heat.m$Outcome)[order(as.numeric(gsub("[^0-9.-]","",unique(heat.m$Outcome))))])
}
heat.m$Amount = gsub(".*\\.","",heat.m$variable)
heat.m$Concentration = case_when(
heat.m$Amount == "L" ~ "Low",
heat.m$Amount == "M" ~ "Mid",
heat.m$Amount == "H" ~ "High",
)
heat.m$Concentration = factor(heat.m$Concentration,c("Low","Mid","High"))
heat.m$SGPV = heat.m$value
print(ggplot(heat.m,aes(x=Concentration,y=Compound,fill=SGPV))+
facet_wrap(~Outcome)+
geom_tile(color="black") + theme_classic() + xlab("") + ylab("") +
scale_fill_gradient2(low="darkred",mid="white",high="black",midpoint=0.5,limits=c(-0.01,1.01),n.breaks = 7 )+
theme(strip.background = element_blank(),
axis.line.x = element_blank(),
axis.line.y = element_blank(),
legend.position="top",
legend.key.width=unit(4,"cm"))
)
}
eff_heatmap = function(heat.df){
breaks = seq(-2,2,0.25)
mycols = colorRampPalette(c("blue","white","red"))(16)
if(ncol(heat.df)/3>=2) {
annotate = data.frame(Out = substr(colnames(heat.df),1,nchar(colnames(heat.df))-1), Amount = factor(substrRight(colnames(heat.df),1),levels=c("L","M","H")))
rownames(annotate) = colnames(heat.df)
Var1 = viridis::viridis(ncol(heat.df)/3)
names(Var1) = c(unique(annotate$Out))
Var2 = rev(viridis::mako(3))
names(Var2) = c(unique(annotate$Amount))
anno_colors = list(Out = Var1,Amount=Var2)
} else {
annotate = data.frame(Amount = factor(substrRight(colnames(heat.df),1),levels=c("L","M","H")))
rownames(annotate) = colnames(heat.df)
Var1 = rev(viridis::mako(3))
names(Var1) = c(unique(annotate$Amount))
anno_colors = list(Amount=Var1)
}
heat.df[which(heat.df > 2,arr.ind=T)] = 2
heat.df[which(heat.df < -2,arr.ind=T)] = -2
# print(pheatmap(heat.df, cluster_rows = F,cluster_cols = F, annotation_col = annotate, annotation_colors =anno_colors, color=mycols,breaks=breaks))
heat.df.gg = heat.df
heat.df.gg$Compound = rownames(heat.df.gg)
heat.m = reshape2::melt(heat.df.gg,id.vars=c("Compound"))
heat.m$Outcome = gsub("\\..*","",heat.m$variable)
if(all(! is.na(as.numeric(substr(heat.m$Outcome,1,1))))){
heat.m$Outcome = factor(heat.m$Outcome,levels=unique(heat.m$Outcome)[order(as.numeric(gsub("[^0-9.-]","",unique(heat.m$Outcome))))])
}
heat.m$Amount = gsub(".*\\.","",heat.m$variable)
heat.m$Concentration = case_when(
heat.m$Amount == "L" ~ "Low",
heat.m$Amount == "M" ~ "Mid",
heat.m$Amount == "H" ~ "High",
)
heat.m$Concentration = factor(heat.m$Concentration,c("Low","Mid","High"))
heat.m$Effect = heat.m$value
heat.m$Effect[heat.m$Effect > 2] = 2
heat.m$Effect[heat.m$Effect < -2] = -2
print(ggplot(heat.m,aes(x=Concentration,y=Compound,fill=Effect))+
facet_wrap(~Outcome)+
geom_tile(color="black") + theme_classic() + xlab("") + ylab("") +
scale_fill_gradient2(low="blue",mid="white",high="red",midpoint=0,limits=c(-2.01,2.01))+
theme(strip.background = element_blank(),
axis.line.x = element_blank(),
axis.line.y = element_blank(),
legend.position="top",
legend.key.width=unit(4,"cm"))
)
}
sig_heatmap = function(heat.df){
if(ncol(heat.df)/3>=2) {
annotate = data.frame(Out = substr(colnames(heat.df),1,nchar(colnames(heat.df))-1), Amount = factor(substrRight(colnames(heat.df),1),levels=c("L","M","H")))
rownames(annotate) = colnames(heat.df)
Var1 = viridis::viridis(ncol(heat.df)/3)
names(Var1) = c(unique(annotate$Out))
Var2 = rev(viridis::mako(3))
names(Var2) = c(unique(annotate$Amount))
anno_colors = list(Out = Var1,Amount=Var2)
} else {
annotate = data.frame(Amount = factor(substrRight(colnames(heat.df),1),levels=c("L","M","H")))
rownames(annotate) = colnames(heat.df)
Var1 = rev(viridis::mako(3))
names(Var1) = c(unique(annotate$Amount))
anno_colors = list(Amount=Var1)
}
breaks = c(-1,-.75,-.5,0,.5,.75,1)
mycols = c("blue","blue","black","black","red","red")
# print(pheatmap(heat.df, cluster_rows = F,cluster_cols = F, annotation_col = annotate, annotation_colors =anno_colors, color=mycols,breaks=breaks,na_col="white"))
heat.df.gg = heat.df
heat.df.gg$Compound = rownames(heat.df.gg)
heat.m = reshape2::melt(heat.df.gg,id.vars=c("Compound"))
heat.m$Result = case_when(
heat.m$value == -1 ~ "Sig Decrease",
heat.m$value == 1 ~ "Sig Increase",
heat.m$value == 0 ~ "Equivalent",
TRUE ~ "Inconclusive"
)
heat.m$Outcome = gsub("\\..*","",heat.m$variable)
if(all(! is.na(as.numeric(substr(heat.m$Outcome,1,1))))){
heat.m$Outcome = factor(heat.m$Outcome,levels=unique(heat.m$Outcome)[order(as.numeric(gsub("[^0-9.-]","",unique(heat.m$Outcome))))])
}
heat.m$Amount = gsub(".*\\.","",heat.m$variable)
heat.m$Concentration = case_when(
heat.m$Amount == "L" ~ "Low",
heat.m$Amount == "M" ~ "Mid",
heat.m$Amount == "H" ~ "High",
)
heat.m$Concentration = factor(heat.m$Concentration,c("Low","Mid","High"))
print(ggplot(heat.m,aes(x=Concentration,y=Compound,fill=Result))+
facet_wrap(~Outcome)+
geom_tile(color="black") + theme_classic() + xlab("") + ylab("") +
scale_fill_manual(values = c("Equivalent" = "black","Inconclusive" = "white", "Sig Increase" = "Red", "Sig Decrease" = "blue"))+
theme(strip.background = element_blank(),
axis.line.x = element_blank(),
axis.line.y = element_blank(),
legend.position="top")
)
}
```
# Data file {.tabset}
For all analyses second generation p-values were used to control the false discovery rate. This method was chosen as it is not reliant on the number of tests run nor is it overly punitive when there are non-independent tests. We have many tests that are at least somewhat dependent because they use the same toxin but at different concentrations. Further, by using second gen p-values we can continually add more and more toxins to the screening without having to incur further penalties (p-vals don't change based on new data). The null interval is based on recommendations from the original methods paper and it is +/-10% for all models. Results are presented in a table of second generation p-values (SGPV) and as heatmaps. SGPV = 0 is considered significant, SGPV =1 is evidence of equivalence, and SGPV = 0.5 is exactly inconclusive. A SGPV = 0.04 is not significant, but it does indicate that there is more evidence of a difference than no difference. These results may just be under powered and could be worth investigating further as a "potential hit". In the effects heatmaps, all results are either log(fold-change) or log(odds), regardless, red indicates the toxin was higher relative to control and blue the toxin was lower.
## TG {.tabset}
```{r}
##This code chunk is for data processing only, but should include all necessary data processing
### Gathering all TG data, combining them into one data frame for easier processing and final plots.
library(DescTools)
df=NULL
all.files = list.files(pattern = ".xlsx$", recursive = TRUE)
for(i in all.files[grepl( "TG", all.files, fixed = TRUE)]){
df1 = as.data.frame(read_excel(i,sheet = 1,skip=2))
df1[,1:2] = LOCF(df1[,1:2])
colnames(df1)[1:3] = c("Toxin","Conc","Rep")
ix = which(tolower(df1$Toxin) == "female" | tolower(df1$Toxin) == "females",arr.ind=T)
if(length(ix)>0){
df1 = df1[1:ix-1,]
}
df1 = df1[df1$Rep != "Average",]
df1$Set = case_when(grepl( "Blue", i, fixed = TRUE)~"Blue",
grepl( "Orange", i, fixed = TRUE)~"Orange",
grepl( "Pink", i, fixed = TRUE)~"Pink",
grepl( "blue", i, fixed = TRUE)~"Blue",
grepl( "orange", i, fixed = TRUE)~"Orange",
grepl( "pink", i, fixed = TRUE)~"Pink",
TRUE~"Check"
)
df1$Compound = sub("/.*", "", i)
df = rbind(df,df1)
}
df=subset(df,select=c('Compound','Toxin','Conc','Rep','weight of 1 fly (g)','OD/weight as % of control', 'OD/#flies as % of control' , 'Set'))
df.m = reshape2::melt(df,id.vars=c('Toxin','Conc','Rep','Set','Compound'))
df.m$Conc[is.na(df.m$Conc)] = ""
df.m$Conc[tolower(df.m$Conc) == "high"] = "H"
df.m$Conc[tolower(df.m$Conc) == "mid"] = "M"
df.m$Conc[tolower(df.m$Conc) == "low"] = "L"
df.m$Conc[df.m$Toxin=="Control"]=""
df.m$Group = paste0(df.m$Toxin,df.m$Conc)
df.m$value = as.numeric(df.m$value)
df.m$Group = gsub(",","",df.m$Group)
df.m$Group = gsub("\\(","",df.m$Group)
df.m$Group = gsub("\\)","",df.m$Group)
df.m$Group = gsub("-","",df.m$Group)
df.m$Group = factor(df.m$Group,levels=unique(df.m$Group))
```
### Exploratory Plots {.tabset}
#### All data
```{r TG_Exploratory, fig.width= 5 + length(unique(df.m$Group))/9.6 ,fig.height = length(unique(df.m$variable))*5.5}
##Code chunk for plots
knitr::kable(table(df$Compound))
## Simple dot plot of all the data
ggplot(na.omit(df.m),aes(x=Group,y=value,color=Group,shape=Set)) +theme_classic(14)+theme(legend.position = "none",axis.text.x = element_text(angle=90,hjust=1))+geom_jitter(height = 0,width=.15)+ scale_color_viridis(discrete=T)+facet_wrap(~variable,scales="free",ncol=1)+xlab("")+theme(strip.background = element_blank())
## Simple bar plot of all the data
agg.d = aggregate(value~Group+variable,df.m,median)
agg.d$gini = aggregate(value~Group+variable,df.m,Hmisc::GiniMd)$value
ggplot(na.omit(agg.d),aes(x=Group,y=value,fill=Group)) +theme_classic(14)+theme(legend.position = "none",axis.text.x = element_text(angle=90,hjust=1))+geom_bar(stat="identity")+
geom_errorbar(aes(ymin=value,ymax=value+gini),width=.15) +
scale_fill_viridis(discrete=T)+facet_wrap(~variable,scales="free",ncol=1)+xlab("")+theme(strip.background = element_blank())
```
```{r TG_Exploratory_Facet, fig.width= 5 + (length(unique(df.m$Compound))+length(unique(df.m$variable)))/2,fig.height = length(unique(df.m$variable))*3.5}
agg.d2 = aggregate(value~Group+variable+Compound,df.m,median)
agg.d2$gini = aggregate(value~Group+variable+Compound,df.m,Hmisc::GiniMd)$value
ggplot() +theme_classic(14)+theme(legend.position = "none",axis.text.x = element_text(angle=90,hjust=1))+geom_errorbar(data=na.omit(agg.d2[agg.d2$variable==unique(agg.d2$variable)[1],]),aes(x=Group,ymin=value,ymax=value,color=Group),width=.7)+
geom_jitter(data = na.omit(df.m[df.m$variable == unique(df.m$variable)[1],]),aes(x=Group,y=value,color=Group,shape=Set),height = 0,width=.35)+ scale_color_viridis(discrete=T)+facet_wrap(~Compound,scales="free",ncol=3)+xlab("")+theme(strip.background = element_blank())+scale_y_continuous(expand=c(0,0))+geom_errorbar(data=na.omit(agg.d2[agg.d2$variable==unique(agg.d2$variable)[1],]),aes(x=Group,ymin=value-gini,ymax=value+gini,color=Group),width=.25)
ggplot() +theme_classic(14)+theme(legend.position = "none",axis.text.x = element_text(angle=90,hjust=1))+geom_errorbar(data=na.omit(agg.d2[agg.d2$variable==unique(agg.d2$variable)[2],]),aes(x=Group,ymin=value,ymax=value,color=Group),width=.7)+
geom_jitter(data = na.omit(df.m[df.m$variable == unique(df.m$variable)[2],]),aes(x=Group,y=value,color=Group,shape=Set),height = 0,width=.35)+ scale_color_viridis(discrete=T)+facet_wrap(~Compound,scales="free",ncol=3)+xlab("")+theme(strip.background = element_blank())+scale_y_continuous(expand=c(0,0))+geom_errorbar(data=na.omit(agg.d2[agg.d2$variable==unique(agg.d2$variable)[2],]),aes(x=Group,ymin=value-gini,ymax=value+gini,color=Group),width=.25)
ggplot() +theme_classic(14)+theme(legend.position = "none",axis.text.x = element_text(angle=90,hjust=1))+geom_errorbar(data=na.omit(agg.d2[agg.d2$variable==unique(agg.d2$variable)[3],]),aes(x=Group,ymin=value,ymax=value,color=Group),width=.7)+
geom_jitter(data = na.omit(df.m[df.m$variable == unique(df.m$variable)[3],]),aes(x=Group,y=value,color=Group,shape=Set),height = 0,width=.35)+ scale_color_viridis(discrete=T)+facet_wrap(~Compound,scales="free",ncol=3)+xlab("")+theme(strip.background = element_blank())+scale_y_continuous(expand=c(0,0))+geom_errorbar(data=na.omit(agg.d2[agg.d2$variable==unique(agg.d2$variable)[3],]),aes(x=Group,ymin=value-gini,ymax=value+gini,color=Group),width=.25)
```
#### Controls Only
```{r TG_Exploratory_Ctrls, fig.width= 5 + (length(unique(df.m$Compound))+length(unique(df.m$variable)))/2 ,fig.height = 6}
## Just the controls
ggplot(na.omit(df.m[df.m$Group == "Control",]),aes(x=Compound,y=value,color=Group,shape=Set)) +theme_classic(14)+theme(legend.position = "bottom",axis.text.x = element_text(angle=45,hjust=1))+geom_jitter(height = 0,width=.15)+ scale_color_viridis(discrete=T)+facet_wrap(~variable,scales="free",ncol=3)+xlab("")+theme(strip.background = element_blank())
```
### Analysis
log 2 transformed robust linear mixed-effects model with a random effect for set (blue, pink, orange). Methods Rationale: the random effects of this model account for the relatedness of replicates within a set which is important for both reducing bias and getting a better estimate of group variance (ie improves power). Ratios such as OD/#flies as % of control and OD/weight as % of control are often right tail heavy; weight can also be right-tailed heavy or roughly Gaussian. A log transformation is a common transformation for right tailed heavy data to improve normality of residuals. The robust part of this regression is to reduce the impact of highly influential individuals (re: outliers) and unequal variances among the groups.
```{r}
#This code chunk is for analyzing the data, it produces 2 data frames, one for second gen p-values and one for effect sizes (log2FC)
res.all=NULL
eff.all=NULL
for(i in unique(df.m$Compound)){
fit = rlmer(log(value)~Group+(1|Set),data=df.m[df.m$variable == 'weight of 1 fly (g)'&df.m$Compound==i,])
res = confint(emmeans(fit,f,adjust="none"))$contrasts
res$SGPV = sgpvalue(
est.lo=res$asymp.LCL,
est.hi=res$asymp.UCL,
null.lo=log(.9),
null.hi=log(1.1),
inf.correction = 1e-05,
warnings = TRUE
)$p.delta
# res$estimate = exp(res$estimate)
colnames(res)=c("Comparison","Fractional Difference","se","df","Low","Up","Second Gen P")
knitr::kable(subset(res,select= c("Comparison","Fractional Difference","Second Gen P")),caption="Differences in the number of pupae")
res.m = res[,c(1,7)]
colnames(res.m)[2] = "Weight of 1 fly (g)"
eff.m = res[,c(1,2)]
colnames(eff.m)[2] = "Weight of 1 fly (g)"
fit = rlmer(log2(value)~Group+(1|Set),data=df.m[df.m$variable == 'OD/weight as % of control'&df.m$Compound==i,])
res = confint(emmeans(fit,f,adjust="none"))$contrasts
res$SGPV = sgpvalue(
est.lo=res$asymp.LCL,
est.hi=res$asymp.UCL,
null.lo=log2(.9),
null.hi=log2(1.1),
inf.correction = 1e-05,
warnings = TRUE
)$p.delta
# res$estimate = 2^(res$estimate)
colnames(res)=c("Comparison","Fractional Difference","se","df","Low","Up","Second Gen P")
knitr::kable(subset(res,select= c("Comparison","Fractional Difference","Second Gen P")),caption="Differences in the number of pupae")
res.t=res[,c(1,7)]
colnames(res.t)[2] = "OD/weight as % of control"
eff.t = res[,c(1,2)]
colnames(eff.t)[2] = "OD/weight as % of control"
fit = rlmer(log2(value)~Group+(1|Set),data=df.m[df.m$variable == 'OD/#flies as % of control' &df.m$Compound==i,])
res = confint(emmeans(fit,f,adjust="none"))$contrasts
res$SGPV = sgpvalue(
est.lo=res$asymp.LCL,
est.hi=res$asymp.UCL,
null.lo=log2(.9),
null.hi=log2(1.1),
inf.correction = 1e-05,
warnings = TRUE
)$p.delta
# res$estimate = 2^(res$estimate)
colnames(res)=c("Comparison","Fractional Difference","se","df","Low","Up","Second Gen P")
knitr::kable(subset(res,select= c("Comparison","Fractional Difference","Second Gen P")),caption="Differences in the number of pupae")
res.c=res[,c(1,7)]
colnames(res.c)[2] = "OD/#flies as % of control"
eff.c = res[,c(1,2)]
colnames(eff.c)[2] = "OD/#flies as % of control"
res.all=rbind(res.all,merge(merge(res.m,res.t),res.c))
eff.all=rbind(eff.all,merge(merge(eff.m,eff.t),eff.c))
}
knitr::kable(res.all,digits=3,caption = "Second Generation P-values")
```
### Results Plots {.tabset}
#### Second Generation P-val Heatmap
```{r TG-Pvals, fig.width=4.5+length(unique(df.m$variable)),fig.height=3+length(unique(df.m$Group))/16.5}
p_val_heatmap(format_heat(res.all))
```
#### log2(fold-change) Heatmap
```{r TG-FC,fig.width=4.5+length(unique(df.m$variable)),fig.height=3+length(unique(df.m$Group))/16.5}
eff_heatmap(format_heat(eff.all))
```
#### Signifcance Summary Heatmap
```{r, fig.width=4.5+length(unique(df.m$variable)),fig.height=3+length(unique(df.m$Group))/16.5}
sig.all = res.all[,2:ncol(res.all)]
sig.all[sig.all != 1 &sig.all !=0] = NA
sig.all= -1*(sig.all-1) * sign(eff.all[,2:ncol(eff.all)])
sig.all=cbind(eff.all[,1],sig.all)
colnames(sig.all)[1]="Comparison"
sig_heatmap(format_heat(sig.all))
```
## Longevity {.tabset}
```{r}
df=NULL
all.files = list.files(pattern = ".xlsx$", recursive = TRUE)
for(i in all.files[grepl( "long", all.files, fixed = TRUE)|grepl( "Long", all.files, fixed = TRUE)]){
#
if(i == "Heavy metals and DBCM 2021/Longevity Blue.xlsx" ){
df.t = as.data.frame(read_excel(i,sheet = 1,skip=0))
colnames(df.t)[substr(colnames(df.t),1,3)=="..."]=NA
colnames(df.t) = na.locf(colnames(df.t), na.rm = FALSE)
df.t = df.t[,c(2,which(df.t[1,] != "Total"& df.t[1,] != "average"))]
colnames(df.t)[3]="Age"
R = df.t[1,3:ncol(df.t)]
R=gsub("\\#","",R)
df.t=df.t[-1,3:ncol(df.t)]
colnames(df.t)[2:ncol(df.t)] = gsub("\\..*","",colnames(df.t)[2:ncol(df.t)])
for(s in 2:ncol(df.t)){
colnames(df.t)[s] = paste0(colnames(df.t)[s],".",R[s])
}
df.t = reshape2::melt(df.t,id.vars=c("Age"))
df.t=df.t[df.t$Age!="Age (days)",]
colnames(df.t)[c(1,2)]=c("variable","Group")
df.t$R = gsub(".*\\.","",df.t$Group)
df.t$Group = gsub("\\..*","",df.t$Group)
df.t$Set = "Blue"
df.t$Compound = "Heavy metals and DBCM 2021"
df.t$variable = as.numeric(as.character(df.t$variable))
df.t$Conc = gsub(".* ","",df.t$Group)
} else {
df.t = as.data.frame(read_excel(i,sheet = 1,skip=4))
colnames(df.t)[1:3] = c("Group","Conc","R")
df.t$Set = case_when(grepl( "Blue", i, fixed = TRUE)~"Blue",
grepl( "Orange", i, fixed = TRUE)~"Orange",
grepl( "Pink", i, fixed = TRUE)~"Pink",
grepl( "blue", i, fixed = TRUE)~"Blue",
grepl( "orange", i, fixed = TRUE)~"Orange",
grepl( "pink", i, fixed = TRUE)~"Pink",
TRUE~"Check"
)
ix = which(tolower(df.t$Group) == "female" | tolower(df.t$Group) == "females",arr.ind=T)
if(length(ix)>0){
df.t = df.t[1:ix-1,]
}
df.t$Group = na.locf(df.t$Group, na.rm = FALSE)
df.t$Conc = na.locf(df.t$Conc, na.rm = FALSE)
df.t$Conc[is.na(df.t$Conc)] = ""
df.t$Group = paste0(df.t$Group,df.t$Conc)
df.t$Compound = sub("/.*", "", i)
df.t = reshape2::melt(df.t,id.vars=c( "Set","Compound","Group","Conc","R"))
df.t$variable = as.character(df.t$variable)
}
df=rbind(df,df.t)
}
df.m = df[!is.na(df$value),]
df.m$Group = gsub("high", "H",df.m$Group)
df.m$Group = gsub("High", "H",df.m$Group)
df.m$Group = gsub("Med", "M",df.m$Group)
df.m$Group = gsub("med", "M",df.m$Group)
df.m$Group = gsub("mid", "M",df.m$Group)
df.m$Group = gsub("Mid", "M",df.m$Group)
df.m$Group = gsub("Low", "L",df.m$Group)
df.m$Group = gsub("low", "L",df.m$Group)
df.m = df.m[df.m$Group != "Date" & df.m$Group != "Age(days)",]
df.m$Group[substr(df.m$Group,1,7)=="Control"] ="Control"
df.m$Conc[substr(df.m$Group,1,7) == "Control"] = ""
df.m$value = as.numeric(df.m$value)
df.m$variable = as.numeric(df.m$variable)
df.m$Group = gsub(",","",df.m$Group)
df.m$Group = gsub("\\(","",df.m$Group)
df.m$Group = gsub("\\)","",df.m$Group)
df.m$Group = gsub("-","",df.m$Group)
df.m$Toxin = substr(as.character(df.m$Group) ,1,nchar(as.character(df.m$Group) )-1)
df.m$Toxin[df.m$Toxin == "Contro"] = "Control"
df.m$Toxin = factor(df.m$Toxin,levels=unique(df.m$Toxin))
df.m$Group = factor(df.m$Group,levels=unique(df.m$Group))
```
### Plots {.tabset}
#### Smoothed Average
```{r, fig.height=5,fig.width=12}
knitr::kable(table(df$Compound))
for(i in unique(df.m$Compound)){
print(ggplot(na.omit(df.m[df.m$R == "% survival"&df.m$variable>14&df.m$variable<60 &df.m$Compound == i,]),aes(x=variable,y=value,color=Group)) +theme_classic(14)+theme(axis.text.x = element_text(angle=90,hjust=1))+ scale_color_viridis(discrete=T)+geom_smooth(se=F,aes(group=Group))+ylab("% Total Survival")+ggtitle(i))
}
```
#### Raw data
```{r, fig.height=5,fig.width=12}
for(i in unique(df.m$Compound)){
print(ggplot(na.omit(df.m[df.m$R == "% survival"&df.m$variable>14&df.m$variable<60 &df.m$Compound == i,]),aes(x=variable,y=value,color=Group,shape=Set)) +theme_classic(14)+theme(axis.text.x = element_text(angle=90,hjust=1))+geom_jitter(height = 0,width=.15)+ scale_color_viridis(discrete=T)+ylab("% Total Survival")+ggtitle(i))
}
# ggplot(na.omit(df.m[df.m$R == "% survival"&df.m$variable>14&df.m$variable<60,]),aes(x=Group,y=value,color=Group,shape=Set)) +theme_classic(14)+theme(axis.text.x = element_text(angle=90,hjust=1),legend.position = "none")+geom_point() + scale_color_viridis(discrete=T)+ylab("% Total Survival")+facet_wrap(~Compound)+ facet_wrap(~variable,ncol=1)
```
#### Time until 50% Dead
A complication of this method is that there are some time points where, for example one group was measured at day 38 and another at day 39. This creates an immortal time bias scenario where, if controls were measured at 38 and a toxin at 39, there's a day where the toxin group cannot die; a difference could be driven entirely by this bias. To get around this we will pool consecutive days and then use a rank-based method (so day 38 and 39 would have the same rank). It's most important that this is done just within a toxin group (eg heavy metals), as data are analyzed by the overall toxin group/class.
```{r Longevity-50, fig.height=5.5,fig.width=5+length(unique(df.m$Group))/9.6}
reps = df.m[df.m$R != "% survival" & df.m$R !="Total",]
# table(reps$variable,reps$Compound)
for(j in unique(reps$Compound)){
ix = which(abs(diff(unique(reps$variable[reps$Compound == j])))<=1)
for(z in ix){
replace = unique(reps$variable[reps$Compound == j])[z]
reps$variable[which(reps$variable == unique(reps$variable[reps$Compound == j])[z] |
reps$variable == unique(reps$variable[reps$Compound == j])[z+1])] = replace
}
}
First.fly = df.m[df.m$R != "% survival" & df.m$R !="Total" & df.m$variable==14,]
colnames(First.fly)[7] = "Start"
reps = left_join(reps,First.fly)
reps$Start=zoo::na.locf(reps$Start)
reps$Percent = reps$value/reps$Start
reps$ID = paste0(reps$Set,reps$Compound,reps$Group,reps$R)
reps = reps[order(reps$variable,decreasing = F),]
reps.50 = reps[reps$Percent<= 0.5,]
reps.50 = reps.50[!duplicated(reps.50$ID),]
reps.50$variable = as.numeric(reps.50$variable)
ggplot(reps.50,aes(x=Group,y=variable,color=Group,shape=Set)) + geom_point()+theme_classic(14)+scale_fill_viridis_d()+theme_classic(14)+theme(axis.text.x = element_text(angle=90,hjust=1),legend.position = "none")+ scale_color_viridis(discrete=T)+ylab("Time until 50% Death")
agg.d = aggregate(variable~Group,reps.50,median)
agg.d$gini = aggregate(variable~Group,reps.50,Hmisc::GiniMd)$variable
ggplot(na.omit(agg.d),aes(x=Group,y=variable,fill=Group)) +theme_classic(14)+theme(legend.position = "none",axis.text.x = element_text(angle=90,hjust=1))+geom_bar(stat="identity")+
geom_errorbar(aes(ymin=variable,ymax=variable+gini),width=.15) +
scale_fill_viridis(discrete=T)+xlab("")+theme(strip.background = element_blank())
```
```{r Longevity_Exploratory_Facet_50, fig.width= 5 + (length(unique(reps.50$Compound))+length(unique(reps.50$variable)))/2,fig.height =3+ length(unique(reps.50$variable))}
agg.d2 = aggregate(variable~Group+Compound,reps.50,median)
agg.d2$gini = aggregate(variable~Group+Compound,reps.50,Hmisc::GiniMd)$variable
ggplot() +theme_classic(14)+theme(legend.position = "none",axis.text.x = element_text(angle=90,hjust=1))+geom_errorbar(data=na.omit(agg.d2),aes(x=Group,ymin=variable,ymax=variable,color=Group),width=.7)+
geom_jitter(data = na.omit(reps.50),aes(x=Group,y=variable,color=Group,shape=Set),height = 0,width=.35)+ scale_color_viridis(discrete=T)+facet_wrap(~Compound,scales="free",ncol=3)+xlab("")+theme(strip.background = element_blank())+scale_y_continuous(expand=c(0,0))+geom_errorbar(data=na.omit(agg.d2),aes(x=Group,ymin=variable-gini,ymax=variable+gini,color=Group),width=.25)
```
##### Controls Only
```{r Longevity_Exploratory_Ctrls_50, fig.width= 2 + (length(unique(reps.50$Compound))+length(unique(reps.50$variable)))/1.5 ,fig.height = 6}
## Just the controls
ggplot(na.omit(reps.50[reps.50$Group == "Control",]),aes(x=Compound,y=variable,color=Group,shape=Set)) +theme_classic(14)+theme(legend.position = "bottom",axis.text.x = element_text(angle=45,hjust=1))+geom_jitter(height = 0,width=.15)+ scale_color_viridis(discrete=T)+xlab("")+theme(strip.background = element_blank())
```
#### Time until 90% Dead
```{r Longevity-90, fig.height=5.5,fig.width=5+length(unique(df.m$Group))/9.6}
reps = df.m[df.m$R != "% survival" & df.m$R !="Total",]
for(j in unique(reps$Compound)){
ix = which(abs(diff(unique(reps$variable[reps$Compound == j])))<=1)
for(z in ix){
replace = unique(reps$variable[reps$Compound == j])[z]
reps$variable[which(reps$variable == unique(reps$variable[reps$Compound == j])[z] |
reps$variable == unique(reps$variable[reps$Compound == j])[z+1])] = replace
}
}
First.fly = df.m[df.m$R != "% survival" & df.m$R !="Total" & df.m$variable==14,]
colnames(First.fly)[7] = "Start"
reps = left_join(reps,First.fly)
reps$Start=zoo::na.locf(reps$Start)
reps$Percent = reps$value/reps$Start
reps$ID = paste0(reps$Set,reps$Compound,reps$Group,reps$R)
reps = reps[order(reps$variable,decreasing = F),]
reps.90 = reps[reps$Percent <= 0.1,]
reps.90 = reps.90[!duplicated(reps.90$ID),]
reps.90$variable = as.numeric(reps.90$variable)
agg.d = aggregate(variable~Group,reps.90,mean)
ggplot(reps.90,aes(x=Group,y=variable,color=Group,shape=Set)) + geom_point()+theme_classic(14)+scale_fill_viridis_d()+theme_classic(14)+theme(axis.text.x = element_text(angle=90,hjust=1),legend.position = "none")+ scale_color_viridis(discrete=T)+ylab("Time until >90% Death")
agg.d = aggregate(variable~Group,reps.90,median)
agg.d$gini = aggregate(variable~Group,reps.90,Hmisc::GiniMd)$variable
ggplot(na.omit(agg.d),aes(x=Group,y=variable,fill=Group)) +theme_classic(14)+theme(legend.position = "none",axis.text.x = element_text(angle=90,hjust=1))+geom_bar(stat="identity")+
geom_errorbar(aes(ymin=variable,ymax=variable+gini),width=.15) +
scale_fill_viridis(discrete=T)+xlab("")+theme(strip.background = element_blank())
```
```{r Longevity_Exploratory_Facet_90, fig.width= 5 + (length(unique(reps.90$Compound))+length(unique(reps.90$variable)))/2,fig.height =3+ length(unique(reps.90$variable))}
agg.d2 = aggregate(variable~Group+Compound,reps.90,median)
agg.d2$gini = aggregate(variable~Group+Compound,reps.90,Hmisc::GiniMd)$variable
ggplot() +theme_classic(14)+theme(legend.position = "none",axis.text.x = element_text(angle=90,hjust=1))+geom_errorbar(data=na.omit(agg.d2),aes(x=Group,ymin=variable,ymax=variable,color=Group),width=.7)+
geom_jitter(data = na.omit(reps.90),aes(x=Group,y=variable,color=Group,shape=Set),height = 0,width=.35)+ scale_color_viridis(discrete=T)+facet_wrap(~Compound,scales="free",ncol=3)+xlab("")+theme(strip.background = element_blank())+scale_y_continuous(expand=c(0,0))+geom_errorbar(data=na.omit(agg.d2),aes(x=Group,ymin=variable-gini,ymax=variable+gini,color=Group),width=.25)
```
##### Controls Only
```{r Longevity_Exploratory_Ctrls_90, fig.width= 2 + (length(unique(reps.90$Compound))+length(unique(reps.90$variable)))/1.5 ,fig.height = 6}
## Just the controls
ggplot(na.omit(reps.90[reps.90$Group == "Control",]),aes(x=Compound,y=variable,color=Group,shape=Set)) +theme_classic(14)+theme(legend.position = "bottom",axis.text.x = element_text(angle=45,hjust=1))+geom_jitter(height = 0,width=.15)+ scale_color_viridis(discrete=T)+xlab("")+theme(strip.background = element_blank())
```
#### AUCs
```{r Longevity-AUC, fig.height=5.5,fig.width=5+length(unique(df.m$Group))/9.6}
library(DescTools)
reps$ID.2 = paste0(reps$Group,reps$Set,reps$R,reps$Compound)
reps.auc = NULL
for(i in unique(reps$ID.2)){
tmp = subset(reps[reps$ID.2 == i,][1,],select=c(Set,Compound,Group,Conc,R,Toxin,ID.2))
tmp$AUC = AUC(reps[reps$ID.2 == i,]$variable,reps[reps$ID.2 == i,]$value)
reps.auc = rbind(reps.auc,tmp)
}
reps.auc$variable = reps.auc$AUC
agg.d = aggregate(variable~Group,reps.auc,median)
agg.d$gini = aggregate(variable~Group,reps.auc,Hmisc::GiniMd)$variable
ggplot(na.omit(agg.d),aes(x=Group,y=variable,fill=Group)) +theme_classic(14)+theme(legend.position = "none",axis.text.x = element_text(angle=90,hjust=1))+geom_bar(stat="identity")+
geom_errorbar(aes(ymin=variable,ymax=variable+gini),width=.15) +
scale_fill_viridis(discrete=T)+xlab("")+theme(strip.background = element_blank())
```
```{r Longevity_Exploratory_Facet_auc, fig.width= 5 + (length(unique(reps.auc$Compound)))/2,fig.height =3+ (length(unique(reps.auc$Compound)))}
agg.d2 = aggregate(variable~Group+Compound,reps.auc,median)
agg.d2$gini = aggregate(variable~Group+Compound,reps.auc,Hmisc::GiniMd)$variable
ggplot() +theme_classic(14)+theme(legend.position = "none",axis.text.x = element_text(angle=90,hjust=1))+geom_errorbar(data=na.omit(agg.d2),aes(x=Group,ymin=variable,ymax=variable,color=Group),width=.7)+
geom_jitter(data = na.omit(reps.auc),aes(x=Group,y=variable,color=Group,shape=Set),height = 0,width=.35)+ scale_color_viridis(discrete=T)+facet_wrap(~Compound,scales="free",ncol=3)+xlab("")+theme(strip.background = element_blank())+scale_y_continuous(expand=c(0,0))+geom_errorbar(data=na.omit(agg.d2),aes(x=Group,ymin=variable-gini,ymax=variable+gini,color=Group),width=.25)
```
##### Controls Only
```{r Longevity_Exploratory_Ctrls_auc, fig.width= 2 + length(unique(reps.auc$Compound)) ,fig.height = 6}
## Just the controls
ggplot(na.omit(reps.auc[reps.auc$Group == "Control",]),aes(x=Compound,y=variable,color=Group,shape=Set)) +theme_classic(14)+theme(legend.position = "bottom",axis.text.x = element_text(angle=45,hjust=1))+geom_jitter(height = 0,width=.15)+ scale_color_viridis(discrete=T)+xlab("")+theme(strip.background = element_blank())
```
### Analysis {.tabset}
#### Results
There are many ways I could see these data being analyzed. Some obvious ones to me are time until 50% total survival and time until 90% death (100% could also make sense, but by going to 90% ie 14/15, we eliminate the cases where one outlying replicate happens to live for much longer by chance, 90% is a hedge). Area under the curves is another interesting one where it would effectively measure the density of deaths over time; a small AUC means flies died quickly, vs a higher AUC means they lived longer overall. One could try to do rate of death, but that will be a 3 or 4 parametric model which we don't have enough data to reliably fit). I've run 50% death, 90% death, and AUC to start but am happy to run others or modify these. The regression method is a cumulative-logit ordinal regression, a random effect was included to account for set (orange, pink, blue). Ordinal regression is similar to a Wilcoxon test, but with a few improvements.
```{r}
res.all=NULL
eff.all=NULL
for(i in unique(df.m$Compound)){
if(length(unique(df.m[df.m$Compound==i,]$Set))>1){
fit = clmm(as.factor(variable)~Group+(1|Set),data=reps.50[reps.50$Compound == i,])
} else {
fit = clm(as.factor(variable)~Group,data=reps.50[reps.50$Compound == i,])
}
res = confint(emmeans(fit,f,adjust="none"))$contrasts
if(any(is.na(res))){
res$SGPV = 0.5
} else {
res$SGPV = sgpvalue(
est.lo=res$asymp.LCL,
est.hi=res$asymp.UCL,
null.lo=log(.9),
null.hi=log(1.1),
inf.correction = 1e-05,
warnings = TRUE
)$p.delta
}
# res$estimate = exp(res$estimate)
colnames(res)=c("Comparison","Fractional Difference","se","df","Low","Up","Second Gen P")
knitr::kable(subset(res,select= c("Comparison","Fractional Difference","Second Gen P")),caption="Differences in the number of pupae")