-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGithub workflow usage instruction.Rmd
2098 lines (1691 loc) · 87.3 KB
/
Github workflow usage instruction.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: "Arson Wildfire data analysis workflow"
output:
md_document:
variant: markdown_github
---
```{r setup, include=FALSE}
knitr::opts_knit$set(root.dir = "C:/Users/huyng/OneDrive - Toronto Metropolitan University/Huy Nguyen/PhD_EnSciMan_Ryerson_University/Arson project/Rproject/data")
knitr::opts_chunk$set(echo = FALSE)
```
## Documentation
This repo is accompanying the publication: "The Use of Computational Fingerprinting Techniques to Distinguish Sources of Accelerants Used in Wildfire Arson".
Users need to first install R with this [link](https://cran.r-project.org/mirrors.html) and Rstudio with this [link](https://posit.co/download/rstudio-desktop/).
This workflow ran on Windows 11 OS 11th Gen Intel(R) Core(TM) i7-11800H \@ 2.30GHz, 16 GB RAM;
THe RStudio version used in this demo is 2023.06.0+421 "Mountain Hydrangea" Release for Windows;
The R version used in this demo is 4.3.1
## Data processing
First, the following R packages are installed and loaded in the global environment along with in-house built functions to minimize repetitiveness in the code.
Details about these functions can be found in Data processing.R file in this repo.
```{r, echo = FALSE, message = FALSE, warning = FALSE}
# Loading Packages --------------------------------------------------------
library(ggplot2)
library(purrr)
library(vegan)
library(readxl)
library(tidyverse)
library(dplyr)
library(data.table)
library(writexl)
library(tidyr)
library(grid)
library(gridExtra)
library(stats)
library(FactoMineR)
library(factoextra)
library(compositions)
library(ggforce)
library(latticeExtra)
library(cluster)
library(umap)
library(plotly)
# library(NADA2)
# library(EnvStats)
# library(CensSpatial)
library(mice)
# Functions -------------------------------------------------------------------------------------------------------
# Notin function
`%notin%` <- Negate(`%in%`)
```
# STEP 1.1: Data import
```{r, echo = FALSE, message = FALSE, warning = FALSE}
target_comp <- read_xlsx(path = "Shortened ILR Compound List PF001A 07-06-2024.xlsx")
# ASTM <- read_xlsx(path = "ILR Compound List 05-15-2024_Without DieselASTM.xlsx")
file_path <- "Gasolines_BOP_110424.xlsx"
dfs <- excel_sheets(file_path) %>%
set_names() %>%
map(~ read_excel(file_path, sheet = .x) %>% mutate(Sample_name = .x))
df_step1.1 <- bind_rows(dfs) %>%
dplyr::select(-c("RMF", "Area %")) %>%
mutate(Octane_rating = ifelse(str_detect(Sample_name, "A"), "Gas_87",
ifelse(str_detect(Sample_name, "B"), "Gas_89",
ifelse(str_detect(Sample_name, "C"), "Gas_91", "Gas_94")))) %>%
mutate(sampling_season = ifelse(str_detect(Sample_name, "b"), "blue",
ifelse(str_detect(Sample_name, "p"), "purple", "orange"))) %>%
mutate(gas_station = ifelse(str_detect(Sample_name, "F001"), "Station_1",
ifelse(str_detect(Sample_name, "F002"), "Station_2",
ifelse(str_detect(Sample_name, "F003"), "Station_3",
ifelse(str_detect(Sample_name, "F004"), "Station_4",
ifelse(str_detect(Sample_name, "F005"), "Station_5",
ifelse(str_detect(Sample_name, "F006"), "Station_6",
ifelse(str_detect(Sample_name, "F007"), "Station_7",
ifelse(str_detect(Sample_name, "F008"), "Station_8",
ifelse(str_detect(Sample_name, "F009"), "Station_9", "Station_10"))))))))))
# modify columns names
colnames(df_step1.1)[colnames(df_step1.1) == '<sup>1</sup>t<sub>R</sub>'] <- 'RT1'
colnames(df_step1.1)[colnames(df_step1.1) == '<sup>2</sup>t<sub>R</sub>'] <- 'RT2'
colnames(df_step1.1)[colnames(df_step1.1) == 'Major'] <- 'Ion1'
colnames(df_step1.1)[colnames(df_step1.1) == 'Qual'] <- 'Ion2'
```
# STEP 1.2: Filtering out column bleed, solvent and BTEX and MF = 0
```{r, echo = FALSE, message = FALSE, warning = FALSE}
filter_list <- c("^Carbon disulfide$",
"Cyclotrisiloxane..hexamethyl",
"Cyclotetrasiloxane..octamethyl"
# "^Benzene$",
# "^Toluene$",
# "^Ethylbenzene$",
# "Xylene"
)
# ^Carbon disulfide$ 75.890 - 75.959, 77.881 - 77.948
df_step1.2 <- copy(df_step1.1) # %>%
# filter(MF > 0)
for (filter_comp in filter_list) {
df_step1.2 <- df_step1.2 %>%
filter(!grepl(filter_comp, Compound))
}
df_step2 <- df_step1.2 %>%
filter(Area > 300000) %>%
arrange(RT1, RT2)
```
#### Quality assurance: Histogram distribution of Peak values before data normalization
```{r class.source = 'fold-hide', echo = FALSE, message = FALSE, warning = FALSE}
ggplot(data = df_step2) +
geom_histogram(aes(x= Area)) +
facet_wrap(~Sample_name) +
theme_minimal(base_size = 20) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5)
# strip.text = element_blank()
)
```
### Plot benchmark distribution for aligning compounds later
```{r, echo = FALSE, message = FALSE, warning = FALSE}
bm_df <- df_step1.1 %>%
filter(grepl("Toluene-D8", Compound)) %>%
filter(RT2 >= 3 & RT2 <= 5)
# Examining Retention time fluctuation of Toluene benchmark
# RT1 hist plot
hist(as.numeric(bm_df$RT1), breaks = 10,
xlab = "RT1", ylab ="", cex.axis = 2, cex.lab = 2, cex.main = 2,
main = "Toluene")
# RT2 hist plot
hist(as.numeric(bm_df$RT2),
xlab = "RT2", ylab ="", cex.axis = 2, cex.lab = 2, cex.main = 2,
main = "Toluene")
```
# QUALITY CONTROL A OF STEP 1.2B: Plot Percentage coverage after removal of limit observation
```{r, echo = FALSE, message = FALSE, warning = FALSE}
plot_a <- list()
i <- 1
for (name in unique(df_step1.2$Sample_name)[50:70]) {
coverage <- c()
for (threshold in c(seq(from = 0, to = 300000, by = 50000))) {
temp <- df_step1.2 %>%
filter(Sample_name %in% name)
df_filter_area <- temp %>%
filter(Area > threshold)
coverage <- c(coverage, sum(df_filter_area$Area)*100/sum(temp$Area))
}
df <- data.frame(thres = seq(from = 0, to = 300000, by = 50000), cover = coverage)
plot_a[[i]] <- ggplot(data = df,
aes(x = thres, y = cover)) +
geom_col() +
theme(text = element_text(size = 10)) +
geom_text(aes(label = round(cover, digits = 3)), color = "green", angle = 90, hjust = 1, size = 5) +
scale_x_continuous(breaks = seq(from = 0, to = 300000, by = 50000),
# remove space between plotted data and xy-axes
expand = c(0,0)) +
scale_y_continuous(breaks = seq(from = 0, to = 100, by = 25),
# remove space between plotted data and xy-axes
expand = c(0,0)) +
ggtitle(name) +
labs(x = NULL, y = NULL)
i <- i + 1
}
y <- textGrob("Percentage coverage of remaining peaks after removal", rot = 90, gp = gpar(fontsize = 20))
x <- textGrob("Threshold of removal for limit observations", gp = gpar(fontsize = 20))
grid.arrange(grobs = plot_a, ncol = 5,
left = y,
bottom = x)
```
# QUALITY CONTROL B OF STEP 1.2B: Plot number of peak remains after removal of limit observation
```{r, echo = FALSE, message = FALSE, warning = FALSE}
plot_b <- list()
i <- 1
for (name in unique(df_step1.2$Sample_name)[50:70]) {
peak_remain <- c()
for (threshold in c(seq(from = 0, to = 300000, by = 50000))) {
temp <- df_step1.2 %>%
filter(Sample_name %in% name)
df_filter_area <- temp %>%
filter(Area > threshold)
peak_remain <- c(peak_remain, dim(df_filter_area)[1])
}
df <- data.frame(thres = seq(from = 0, to = 300000, by = 50000), remain = peak_remain)
plot_b[[i]] <- ggplot(data = df,
aes(x = thres, y = remain)) +
geom_col() +
geom_text(aes(label = remain), color = "green", vjust = 1.2, size = 5) +
scale_x_continuous(breaks = seq(from = 0, to = 300000, by = 50000),
# remove space between plotted data and xy-axes
expand = c(0,0)) +
ggtitle(name) +
theme(axis.text.x = element_text(size = 20),
axis.text.y = element_text(size = 20)) +
labs(x = NULL, y = NULL) +
theme_classic()
i <- i + 1
}
y <- textGrob("Number of peak remains after removal of limit observation", rot = 90, gp = gpar(fontsize = 15))
x <- textGrob("Threshold of removal for limit observations", gp = gpar(fontsize = 15))
grid.arrange(grobs = plot_b, ncol = 5,
left = y,
bottom = x)
```
## QUALITY CONTROL TO SELECT ALIGNMENT WINDOW: Confirming targeted compounds at each step of Data processing
(Update 22nd May 2024:) Using the target compound list, we will review 18 samples (6 samples across 3 seasons (p,b,o)) to determine how many samples have the target compounds. This data will help determine the effectiveness of the compression - similar to your microplastic table.
We want to make sure that it works for all potential types of fuels.
For the reporting table, there will be cases where the target compounds might not occur in some samples. The best alignment window will be the one that have highest **"Proportion"** = samples have the target compounds/ 71 (total number of samples in the dataset).
Then, I pick the combination of Rt1 and Rt2 that results in the highest cumulative sum of the **"Proportion"** from all target compound by using **rowSums**.
```{r, echo = FALSE, message = FALSE, warning = FALSE}
# For each target compounds, Apply different alignment windows and record number of samples that have the =target compounds
combi <- tidyr::crossing(
# RT1
c(0.1 ,0.15, 0.2, 0.25, 0.3, 0.35, 0.4),
# RT2
c(0.12,0.13,0.14,0.15, 0.16, 0.17, 0.18, 0.19, 0.2))
df <- data.frame(RT1_window=integer(), RT2_window=integer(), target=character(), proportion=integer())
for (i in 1:nrow(combi)) {
for (j in 1:nrow(target_comp)) {
# Catch all peaks in dataframe that falling into the window with target compounds as center of the window
idx1 <- which((df_step2$Ion1 <= (target_comp[j,]$Ion1 + 0.1) & df_step2$Ion1 >= (target_comp[j,]$Ion1 - 0.1) &
df_step2$Ion2 <= (target_comp[j,]$Ion2 + 0.1) & df_step2$Ion2 >= (target_comp[j,]$Ion2 - 0.1)) |
(df_step2$Ion1 <= (target_comp[j,]$Ion2 + 0.1) & df_step2$Ion1 >= (target_comp[j,]$Ion2 - 0.1) &
df_step2$Ion2 <= (target_comp[j,]$Ion1 + 0.1) & df_step2$Ion2 >= (target_comp[j,]$Ion1 - 0.1)))
temp <- df_step2[idx1,]
minrt1 <- max(temp$RT1)
maxrt1 <- min(temp$RT1)
minrt2 <- max(temp$RT2)
maxrt2 <- max(temp$RT2)
idx2 <- which(temp$RT1 <= (target_comp[j,]$RT1 + as.numeric(combi[i,][1])) &
temp$RT1 >= (target_comp[j,]$RT1 - as.numeric(combi[i,][1])) &
temp$RT2 <= (target_comp[j,]$RT2 + as.numeric(combi[i,][2])) &
temp$RT2 >= (target_comp[j,]$RT2 - as.numeric(combi[i,][2])))
df[nrow(df) + 1,] <- c(as.numeric(combi[i,][1]),
as.numeric(combi[i,][2]),
target_comp[j,]$Compound,
# paste0(length(unique(temp[idx2,]$Sample_name)), "/", 71))
100*(length(unique(temp[idx2,]$Sample_name)) / length(unique(temp$Sample_name))))
}
}
summary_df <- df %>% pivot_wider(names_from = target, values_from = proportion)
# Which window have the highest proportion of samples that have the target compounds
summary_df[, 3:ncol(summary_df)] <- lapply(summary_df[, 3:ncol(summary_df)], as.numeric)
max_row <- summary_df[which.max(rowSums(summary_df[, 3:ncol(summary_df)])), ]
print(max_row)
# Adding the number of samples where the compounds were found with matching Ion1 and Ion2 to colnames of each compound
i <- 3
for (j in 1:nrow(target_comp)) {
idx1 <- which((df_step2$Ion1 <= (target_comp[j,]$Ion1 + 0.1) & df_step2$Ion1 >= (target_comp[j,]$Ion1 - 0.1) &
df_step2$Ion2 <= (target_comp[j,]$Ion2 + 0.1) & df_step2$Ion2 >= (target_comp[j,]$Ion2 - 0.1)) |
(df_step2$Ion1 <= (target_comp[j,]$Ion2 + 0.1) & df_step2$Ion1 >= (target_comp[j,]$Ion2 - 0.1) &
df_step2$Ion2 <= (target_comp[j,]$Ion1 + 0.1) & df_step2$Ion2 >= (target_comp[j,]$Ion1 - 0.1)))
temp <- df_step2[idx1,]
idx2 <- which(temp$RT1 <= (target_comp[j,]$RT1 + as.numeric(max_row$RT1_window)) &
temp$RT1 >= (target_comp[j,]$RT1 - as.numeric(max_row$RT1_window)) &
temp$RT2 <= (target_comp[j,]$RT2 + as.numeric(max_row$RT2_window)) &
temp$RT2 >= (target_comp[j,]$RT2 - as.numeric(max_row$RT2_window)))
colnames(summary_df)[i] <- paste0(target_comp[j,]$Compound, " (n = ", length(unique(temp$Sample_name)), ")")
i <- i + 1
}
writexl::write_xlsx(summary_df, path = paste0(getwd(), "/Testing combinations of Retention time window for compound alignment.xlsx"))
```
# QUALITY CONTROL: Examine the distribution of RT of target compounds after alignment with pF001A
```{r, echo = FALSE, message = FALSE, warning = FALSE}
# Get the column names from the existing data frame
column_names <- c( "Target compound", "RT", "Retention time of pF001A", "Min.", "1st Qu.", "Median", "Mean", "3rd Qu.", "Max.", "Max. RT - Min. RT")
# Create an empty data frame with the same column names
summary_df <- data.frame(matrix(ncol = length(column_names), nrow = 0))
colnames(summary_df) <- column_names
summary_target_compounds <- list()
for (j in 1:nrow(target_comp)) {
# First for each target compound, matching Major and minor ion
idx1 <- which((df_step2$Ion1 <= (target_comp[j,]$Ion1 + 0.2) & df_step2$Ion1 >= (target_comp[j,]$Ion1 - 0.2) &
df_step2$Ion2 <= (target_comp[j,]$Ion2 + 0.2) & df_step2$Ion2 >= (target_comp[j,]$Ion2 - 0.2)) |
(df_step2$Ion1 <= (target_comp[j,]$Ion2 + 0.2) & df_step2$Ion1 >= (target_comp[j,]$Ion2 - 0.2) &
df_step2$Ion2 <= (target_comp[j,]$Ion1 + 0.2) & df_step2$Ion2 >= (target_comp[j,]$Ion1 - 0.2)))
temp <- df_step2[idx1,]
# Then, for each target compound, matching within RT +- 0.1 wrt the pF001A retention time.
idx2 <- which(temp$RT1 <= (target_comp[j,]$RT1 + 0.1) &
temp$RT1 >= (target_comp[j,]$RT1 - 0.1) &
temp$RT2 <= (target_comp[j,]$RT2 + 0.1) &
temp$RT2 >= (target_comp[j,]$RT2 - 0.1))
if (nrow(temp[idx2, ]) == 0) {
summary_df[nrow(summary_df) + 1,] <- c(paste0(target_comp[j,]$Compound, " was not found with matching ions and within RT1/RT2 windows of 0.1 of pF001A"), NA, NA, NA, NA, NA, NA, NA, NA, NA)
} else {
# Make descriptive stats summary of RT1 of all peaks that was aligned to target compound in pF001A
summary_df[nrow(summary_df) + 1,] <- c(target_comp[j,]$Compound,
"RT1",
as.numeric(target_comp[j,]$RT1),
as.numeric(summary(as.numeric(temp[idx2,]$RT1))[[1]]),
as.numeric(summary(as.numeric(temp[idx2,]$RT1))[[2]]),
as.numeric(summary(as.numeric(temp[idx2,]$RT1))[[3]]),
as.numeric(summary(as.numeric(temp[idx2,]$RT1))[[4]]),
as.numeric(summary(as.numeric(temp[idx2,]$RT1))[[5]]),
as.numeric(summary(as.numeric(temp[idx2,]$RT1))[[6]]),
as.numeric(summary(as.numeric(temp[idx2,]$RT1))[[6]] - summary(as.numeric(temp[idx2,]$RT1))[[1]]))
# Make descriptive stats summary of RT2 of all peaks that was aligned to target compound in pF001A
summary_df[nrow(summary_df) + 1,] <- c(target_comp[j,]$Compound,
"RT2",
as.numeric(target_comp[j,]$RT2),
as.numeric(summary(as.numeric(temp[idx2,]$RT2))[[1]]),
as.numeric(summary(as.numeric(temp[idx2,]$RT2))[[2]]),
as.numeric(summary(as.numeric(temp[idx2,]$RT2))[[3]]),
as.numeric(summary(as.numeric(temp[idx2,]$RT2))[[4]]),
as.numeric(summary(as.numeric(temp[idx2,]$RT2))[[5]]),
as.numeric(summary(as.numeric(temp[idx2,]$RT2))[[6]]),
as.numeric(summary(as.numeric(temp[idx2,]$RT2))[[6]] - summary(as.numeric(temp[idx2,]$RT2))[[1]]))
# Make histogram of distribution of RT of these target compound
# par(mfrow = c(1, 2))
# hist(as.numeric(temp[idx2,]$RT1),
# xlab = "RT1", ylab ="", cex.axis = 2, cex.lab = 2, cex.main = 1,
# main = paste0("RT1 of ", target_comp[j,]$Compound, "\n with pF001A's RT1 = ", target_comp[j,]$RT1, " and RT1 window = 0.1"))
#
# hist(as.numeric(temp[idx2,]$RT2),
# xlab = "RT2", ylab ="", cex.axis = 2, cex.lab = 2, cex.main = 1,
# main = paste0("RT2 of ", target_comp[j,]$Compound, "\n in pF001A's RT2 = ", target_comp[j,]$RT2, " and RT2 window = 0.1"))
# Reset the layout to default
# par(mfrow = c(1, 1))
}
}
View(summary_df)
writexl::write_xlsx(summary_df, path = paste0(getwd(), "/summary of target compounds matching by major and minor ions and rt1_rt2 of (0.1)_", format(Sys.Date(), "%d-%m-%y"), ".xlsx"))
```
# Make a table for the compounds that was not found in all samples, give the names of the samples where these target compounds are missing
***If the compound can be found in all samples then plot it with x-axis as 71 samples sorted from gas_station 1 to 10, the legend is the sampling season***
(Update 31 May 2024): For the bar plot of target compounds, if the compounds were not presented in a station -> it will have zeros values instead of NA -> it is show in the plot that the compound was not there in certain gas stations.
```{r, echo = FALSE, message = FALSE, warning = FALSE}
summary_df2 <- data.frame(target=character(), samples_that_missing_target_compound=character())
df_step2 <- df_step2 %>%
mutate(gas_station = factor(gas_station, levels = unique(df_step2$gas_station)))
for (j in 1:nrow(target_comp)) {
idx1 <- which((df_step2$Ion1 <= (target_comp[j,]$Ion1 + 0.1) & df_step2$Ion1 >= (target_comp[j,]$Ion1 - 0.1) &
df_step2$Ion2 <= (target_comp[j,]$Ion2 + 0.1) & df_step2$Ion2 >= (target_comp[j,]$Ion2 - 0.1)) |
(df_step2$Ion1 <= (target_comp[j,]$Ion2 + 0.1) & df_step2$Ion1 >= (target_comp[j,]$Ion2 - 0.1) &
df_step2$Ion2 <= (target_comp[j,]$Ion1 + 0.1) & df_step2$Ion2 >= (target_comp[j,]$Ion1 - 0.1)))
temp <- df_step2[idx1,]
idx2 <- which(temp$RT1 <= (target_comp[j,]$RT1 + as.numeric(max_row$RT1_window)) &
temp$RT1 >= (target_comp[j,]$RT1 - as.numeric(max_row$RT1_window)) &
temp$RT2 <= (target_comp[j,]$RT2 + as.numeric(max_row$RT2_window)) &
temp$RT2 >= (target_comp[j,]$RT2 - as.numeric(max_row$RT2_window)))
if (length(unique(temp[idx2,]$Sample_name)) < 71) {
summary_df2[nrow(summary_df2) + 1,] <- c(target_comp[j,]$Compound,
paste(setdiff(unique(df_step2$Sample_name),
unique(temp[idx2,]$Sample_name)),
collapse = ", "))
# Artificial add in the missing samples and put the Area of those sample to be 0
empty_df <- temp[idx2,] %>% select(Area, Sample_name, Octane_rating, sampling_season, gas_station) %>% slice(0)
new_rows <- data.frame(
Area = rep(0, length(setdiff(unique(df_step2$Sample_name),
unique(temp[idx2,]$Sample_name)))),
Sample_name = setdiff(unique(df_step2$Sample_name),
unique(temp[idx2,]$Sample_name)),
Octane_rating = rep(NA, length(setdiff(unique(df_step2$Sample_name),
unique(temp[idx2,]$Sample_name)))),
sampling_season = rep(NA, length(setdiff(unique(df_step2$Sample_name),
unique(temp[idx2,]$Sample_name)))),
gas_station = rep(NA, length(setdiff(unique(df_step2$Sample_name),
unique(temp[idx2,]$Sample_name))))
)
temp2 <- bind_rows(empty_df, new_rows) %>%
mutate(Octane_rating = ifelse(str_detect(Sample_name, "A"), "Gas_87",
ifelse(str_detect(Sample_name, "B"), "Gas_89",
ifelse(str_detect(Sample_name, "C"), "Gas_91", "Gas_94")))) %>%
mutate(sampling_season = ifelse(str_detect(Sample_name, "b"), "blue",
ifelse(str_detect(Sample_name, "p"), "purple", "orange"))) %>%
mutate(gas_station = ifelse(str_detect(Sample_name, "F001"), "Station_1",
ifelse(str_detect(Sample_name, "F002"), "Station_2",
ifelse(str_detect(Sample_name, "F003"), "Station_3",
ifelse(str_detect(Sample_name, "F004"), "Station_4",
ifelse(str_detect(Sample_name, "F005"), "Station_5",
ifelse(str_detect(Sample_name, "F006"), "Station_6",
ifelse(str_detect(Sample_name, "F007"), "Station_7",
ifelse(str_detect(Sample_name, "F008"), "Station_8",
ifelse(str_detect(Sample_name, "F009"), "Station_9", "Station_10")))))))))) %>%
mutate(new_sample_name = paste0(Sample_name, "_", gas_station, "_", Octane_rating))
plotdata <- bind_rows(temp2, temp[idx2,] %>%
select(Area, Sample_name, Octane_rating, sampling_season, gas_station) %>%
mutate(new_sample_name = paste0(Sample_name, "_", gas_station, "_", Octane_rating)))
print(ggplot(data = plotdata, aes(x = new_sample_name , y = Area, fill = sampling_season)) +
geom_bar(stat = "identity") +
labs(title = target_comp[j,]$Compound,
x = "Samples", y = "Peak Area",
fill = "") +
theme_minimal(base_size = 15) +
theme(axis.text.x = element_text(angle = 90, hjust =0.5, vjust = 0.25, color = "black", face = "bold"),
plot.title = element_text(size = 25),
axis.ticks.length.x = unit(0, "cm"),
panel.grid.minor.x = element_blank(),
panel.grid.minor.y = element_blank()) +
scale_y_continuous(expand = c(0,0)))
} else {
temp2 <- temp[idx2,] %>%
mutate(new_sample_name = paste0(Sample_name, "_", gas_station, "_", Octane_rating))
print(ggplot(data = temp2, aes(x = new_sample_name , y = Area, fill = sampling_season)) +
geom_bar(stat = "identity") +
labs(title = target_comp[j,]$Compound,
x = "Samples", y = "Peak Area",
fill = "") +
theme_minimal(base_size = 15) +
theme(axis.text.x = element_text(angle = 90, hjust =0.5, vjust = 0.25, color = "black", face = "bold"),
plot.title = element_text(size = 25),
axis.ticks.length.x = unit(0, "cm"),
panel.grid.minor.x = element_blank(),
panel.grid.minor.y = element_blank()) +
scale_y_continuous(expand = c(0,0)))
}
}
writexl::write_xlsx(summary_df2, path = paste0(getwd(), "/Samples where target compounds are missing.xlsx"))
```
# STEP 2: Grouping compounds based on RT1, RT2, Ion1, Ion2
```{r, echo = FALSE, message = FALSE, warning = FALSE}
# Define tolerances
tolerances <- list(RT1 = 0.1, RT2 = 0.1, Ion1 = 0.5, Ion2 = 0.5)
# Use pF001A as a base
df_all <- df_step2 %>%
filter(Sample_name %in% "pF001A") %>%
filter(`Signal to Noise` > 10)
df_all$Feature <- 1:nrow(df_all)
# Loop through the samples apart from pF001A
for (sample in setdiff(unique(df_step2$Sample_name), c("pF001A", "bF001A", "bF007B"))) {
# print(sample)
df <- df_step2 %>%
filter(Sample_name %in% sample) %>%
filter(`Signal to Noise` > 10)
df$Feature <- NA
# Go through each row
for (i in 1:nrow(df)) {
row <- df[i, ]
mask <- (
abs(df_all$RT1 - row$RT1) <= tolerances$RT1 &
abs(df_all$RT2 - row$RT2) <= tolerances$RT2 &
abs(df_all$Ion1 - row$Ion1) <= tolerances$Ion1 &
abs(df_all$Ion2 - row$Ion2) <= tolerances$Ion2
)
idx <- which(mask)
# If there is a match between a peak and the existing peak list, then assign the same Feature number to that peak
if (any(mask)) {
row$Feature <- unique(df_all[idx, ]$Feature)[1]
} else { # If not a match, then create new identity for the new Feature
row$Feature <- max(df_all$Feature) + 1
}
# adding the peak that have matchs in df_all
df_all <- bind_rows(df_all, row)
}
}
df_all <- df_all %>%
# remove all peak with RT1 > 36 (which does not belong Gasoline)
filter(RT1 < 30)
# Create metadata for next data analysis
metadata <- df_all %>%
dplyr::select(
Feature,
Sample_name,
Area) %>%
group_by(Feature,
Sample_name) %>%
dplyr::summarise(across(Area, base::mean)) %>%
tidyr::pivot_wider(names_from = Sample_name,
values_from = Area)
#### Adding avg RT and Ions to the master df for Gwen
mean_rt1 <- c()
mean_rt2 <- c()
mean_ion1 <- c()
mean_ion2 <- c()
for (i in 1:nrow(metadata)) {
mean_rt1 <- c(mean_rt1, mean(df_all[which(df_all$Feature %in% metadata[i, ]$Feature),]$RT1))
mean_rt2 <- c(mean_rt2, mean(df_all[which(df_all$Feature %in% metadata[i, ]$Feature),]$RT2))
mean_ion1 <- c(mean_ion1, mean(df_all[which(df_all$Feature %in% metadata[i, ]$Feature),]$Ion1))
mean_ion2 <- c(mean_ion2, mean(df_all[which(df_all$Feature %in% metadata[i, ]$Feature),]$Ion2))
}
metadata$RT1 <- mean_rt1
metadata$RT2 <- mean_rt2
metadata$Ion1 <- mean_ion1
metadata$Ion2 <- mean_ion2
metadata <- metadata %>% relocate(RT1, RT2, Ion1, Ion2, .after = 1)
#### Adding Chemical groups of to the master df for Gwen
chemical_group <- c()
for (i in 1:nrow(metadata)) {
idx <- which(abs(metadata[i,]$Ion1 -target_comp$Ion1) <= 0.5 &
abs(metadata[i,]$Ion2 -target_comp$Ion2) <= 0.5 &
abs(metadata[i,]$RT1 -target_comp$RT1) <= 0.1 &
abs(metadata[i,]$RT2 -target_comp$RT2) <= 0.1)
if (identical(idx, integer(0))) {
chemical_group <- c(chemical_group, "unknown")
next
} else {
chemical_group <- c(chemical_group, unique(target_comp[idx,]$Group))
}
}
metadata$Chemical_group <- chemical_group
metadata <- metadata %>% relocate(Chemical_group, .after = 1)
# Export masterlist and metadata for Gwen
# writexl::write_xlsx(df_all, path = paste0("MasterList_", format(Sys.Date(), format = "%d-%b-%Y"), ".xlsx"))
# writexl::write_xlsx(metadata_export, path = paste0("PeakTable_", format(Sys.Date(), format = "%d-%b-%Y"), ".xlsx"))
```
(Update 22nd May 2024:) The alignment is based on pF001A, align all peaks in data set with each peak of pF001A.
### Subset compound that only appear in 1 gas station
```{r class.source = 'fold-hide', echo = FALSE, message = FALSE, warning = FALSE}
unique_comp <- c()
for (feature in unique(df_all$Feature)) {
if (length(unique(df_all[which(df_all$Feature == feature),]$Sample_name)) < 2) {
unique_comp <- c(unique_comp, feature)
}
}
# A). dataset with non-unique compounds
new_df <- metadata %>% filter(Feature %notin% unique_comp)
# B). dataset with only unique compounds
unique_df <- metadata %>% filter(Feature %in% unique_comp)
```
# STEP 3: Feature elimination/ Feature prioritization
### (Update 20th June 2024): SELECT COMPOUNDS THAT belongs to the target compound’s Chemical Group ----------------
```{r, echo = FALSE, message = FALSE, warning = FALSE}
metadata <- metadata %>%
# filter(., Chemical_group %notin% "unknown") %>%
arrange(Chemical_group, RT1, RT2)
```
### Combine data from chemical groups
```{r, echo = FALSE, message = FALSE, warning = FALSE}
# new_metadata <- metadata %>%
# group_by(Chemical_group) %>%
# summarize(across(everything(), sum, na.rm = TRUE))
```
### 1. Via REMOVE COMPOUNDS THAT HAVE < x% MISSING VALUES ----------------
```{r, echo = FALSE, message = FALSE, warning = FALSE}
less_na <- c()
for (row in 1:nrow(metadata)) {
# Filter our compounds that have more than x % NA values
if (sum(is.na(metadata[row,7:ncol(metadata)]))/dim(metadata[,7:ncol(metadata)])[2] <= 0.9) {
less_na <- c(less_na, row)
}
}
if (!is.null(less_na)) {
metadata_na_remove <- metadata[less_na,]
}
```
### 2. Via Investigate data distribution of compounds with high mean and high/low std
```{r, echo = FALSE, message = FALSE, warning = FALSE}
# Investigate data distribution for removal of compounds with high mean and low variance
# hist((shared_comp_alignment %>%
# filter(Area < 10000000))$Area)
summary_table <- new_df %>% # metadata_na_remove %>%
ungroup() %>%
rowwise() %>%
mutate(mean_area = mean(c_across(7:ncol(.)), na.rm = TRUE),
sd_area = sd(c_across(7:ncol(.)), na.rm = TRUE)) %>%
ungroup() %>%
relocate(mean_area, sd_area, .before = 1)
# View(summary_table %>% arrange(desc(mean_area), desc(sd_area)))
highmean_highstd <- list()
i <- 1
for (num_feature in c(25,50,100,200)) {
# Adding back the labelling to metadata
highmean_highstd[[i]] <- as.data.frame(t((summary_table %>% arrange(desc(mean_area), desc(sd_area)))[1:num_feature,] %>% #
# filter(Feature %in% unique(highmean_highstd$Feature)) %>% # Select compounds with high peak area's mean and std.
dplyr::select(-c("Chemical_group", "RT1",
"RT2", "Ion1", "Ion2", "mean_area", "sd_area")) %>%
column_to_rownames(., var = "Feature"))) %>%
rownames_to_column(., var="Sample_name") %>%
mutate(Octane_rating = ifelse(str_detect(Sample_name, "A"), "Gas 87",
ifelse(str_detect(Sample_name, "B"), "Gas 89",
ifelse(str_detect(Sample_name, "C"), "Gas 91", "Gas 94")))) %>%
mutate(sampling_season = ifelse(str_detect(Sample_name, "b"), "blue",
ifelse(str_detect(Sample_name, "p"), "purple", "orange"))) %>%
mutate(gas_station = ifelse(str_detect(Sample_name, "F001"), "Station 1",
ifelse(str_detect(Sample_name, "F002"), "Station 2",
ifelse(str_detect(Sample_name, "F003"), "Station 3",
ifelse(str_detect(Sample_name, "F004"), "Station 4",
ifelse(str_detect(Sample_name, "F005"), "Station 5",
ifelse(str_detect(Sample_name, "F006"), "Station 6",
ifelse(str_detect(Sample_name, "F007"), "Station 7",
ifelse(str_detect(Sample_name, "F008"), "Station 8",
ifelse(str_detect(Sample_name, "F009"), "Station 9", "Station 10")))))))))) %>%
# Add info on Suppliers
mutate(supplier = ifelse(str_detect(Sample_name, "F001"), "Miscellanous",
ifelse(str_detect(Sample_name, "F002"), "Miscellanous",
ifelse(str_detect(Sample_name, "F003"), "Shell",
ifelse(str_detect(Sample_name, "F004"), "Cenovus",
ifelse(str_detect(Sample_name, "F005"), "Miscellanous",
ifelse(str_detect(Sample_name, "F006"), "Suncor",
ifelse(str_detect(Sample_name, "F007"), "Imperial",
ifelse(str_detect(Sample_name, "F008"), "Burnaby",
ifelse(str_detect(Sample_name, "F009"), "Imperial", "unknown")))))))))) %>%
relocate(Octane_rating, sampling_season, gas_station, supplier, .after = 1)
i <- i + 1
}
# ggplot(data = plotdf %>% mutate(Feature = factor(Feature, levels = unique(Feature))), aes(x=Feature, y = mean_area)) +
# geom_bar(stat = 'identity', position = position_dodge(width = 0.9)) +
# geom_errorbar(aes(ymin = mean_area - sd_area,
# ymax = mean_area + sd_area, colour = "red")) +
# ggtitle("Rank 1:100") +
# theme_classic(base_size = 15) +
# theme(axis.text.x = element_text(angle = 90, vjust = 0.5))
```
# STEP 4: Missing value imputation
(Update 21 April 2024:) After remove compounds appear in only one sample and compounds that have >90% Missing values -> plot histogram of distribution -> most of compounds are < 2e+06 => try filter all peaks that is >= 2e+06
## Option 1: 0.001
(UPDATE 17th Jul 2024: Meeting with Bonnie Hamilton and Eric Fries)
```{r, echo = FALSE, message = FALSE, warning = FALSE}
df_0.001 <- list()
for (i in 1:length(highmean_highstd)) {
df_0.001[[i]] <- highmean_highstd[[i]]
for (r in 1:nrow(df_0.001[[i]])) {
df_0.001[[i]][r, which(base::is.na(df_0.001[[i]][r,]))] <- 0.001
}
}
```
## Option 2: LOD
LOD = go through each row of the df and replacing missing values = the lowest values of each sample * 3
```{r , echo=FALSE, warning = FALSE, message=FALSE}
df_lod <- list()
for (i in 1:length(highmean_highstd)) {
df_lod[[i]] <- highmean_highstd[[i]]
for (r in 1:nrow(df_lod[[i]])) {
df_lod[[i]][r, 6:ncol(df_lod[[i]])][,which(base::is.na(df_lod[[i]][r, 6:ncol(df_lod[[i]])]))] <- 3*min(df_lod[[i]][r, 6:ncol(df_lod[[i]])][,which(!base::is.na(df_lod[[i]][r, 6:ncol(df_lod[[i]])]))])
}
}
```
## Option 3: Randomized values drawn from uniform distribution of the two global minimum values
```{r , echo=FALSE, warning = FALSE, message=FALSE}
min_df <- list()
for (i in 1:length(highmean_highstd)) {
min_df[[i]] <- highmean_highstd[[i]]
for (r in 1:nrow(min_df[[i]])) {
min_df[[i]][r, which(base::is.na(min_df[[i]][r,]))] <- as.list(runif(length(which(is.na(min_df[[i]][r,]))),
min = 0,
max = sort(df_all$Area)[1]))
}
}
```
## Option 4: with mice
'cart', 'rf', 'sample', "2l.lmer" is quite robust when the matrix has linearly dependent columns or is near-singular due to multicollinearity or insufficient variation in the data.
'rf' still resulted in missing values after complete(imp) -> consider not using it
```{r, echo = FALSE, message = FALSE, warning = FALSE}
mice_df <- list()
for (i in 1:length(highmean_highstd)) {
mice_df[[i]] <- highmean_highstd[[i]][,-c(1,2,3,4,5)]
colnames(mice_df[[i]]) <- paste0("Comp_", colnames(mice_df[[i]]))
imp <- mice(mice_df[[i]], method = "cart", ridge = 0.0001, threshold=1.1)
imp_df <- complete(imp)
mice_df[[i]]<- cbind(highmean_highstd[[i]][,c(1,2,3,4,5)], imp_df)
}
for (i in 1:length(mice_df)) {
temp <- mice_df[[i]][,-c(1,2,3,4,5)]
for (col in 1:ncol(temp)) {
colnames(temp)[col] <- unlist(strsplit(colnames(temp)[col], split = "_"))[2]
}
mice_df[[i]]<- cbind(highmean_highstd[[i]][,c(1,2,3,4,5)], temp)
}
```
# STEP 5: Data Normalization
### Percentage-based normalization
```{r, echo = FALSE, message = FALSE, warning = FALSE}
input <- df_0.001
percentage_normalized <- list()
for (i in 1:length(input)) {
percentage_normalized[[i]] <- as.data.frame(t(apply(input[[i]][, 6:ncol(input[[i]])],
MARGIN = 1,
function(row) {row/sum(row, na.rm = TRUE)})))
percentage_normalized[[i]] <- percentage_normalized[[i]] %>%
mutate(Octane_rating = input[[i]]$Octane_rating) %>%
mutate(sampling_season = input[[i]]$sampling_season) %>%
mutate(gas_station = input[[i]]$gas_station) %>%
mutate(Sample_name = input[[i]]$Sample_name) %>%
mutate(supplier = input[[i]]$supplier) %>%
relocate(Octane_rating, sampling_season, gas_station, Sample_name, supplier, .before = 1)
}
```
### Log normalization
```{r, echo = FALSE, message = FALSE, warning = FALSE}
input <- mice_df
log_normalized <- list()
for (i in 1:length(input)) {
log_normalized[[i]] <- as.data.frame(t(apply(input[[i]][, 6:ncol(input[[i]])],
MARGIN = 1, function(x) log(x))))
log_normalized[[i]] <- log_normalized[[i]] %>%
mutate(Octane_rating = input[[i]]$Octane_rating) %>%
mutate(sampling_season = input[[i]]$sampling_season) %>%
mutate(gas_station = input[[i]]$gas_station) %>%
mutate(Sample_name = input[[i]]$Sample_name) %>%
mutate(supplier = input[[i]]$supplier) %>%
relocate(supplier, Octane_rating, sampling_season, gas_station, Sample_name, .before = 1)
}
```
# Exploratory Data Analysis
## Stacked bar plot of significant compounds and associated suppliers
```{r, echo = FALSE, message = FALSE, warning = FALSE}
df <- p_test %>%
pivot_longer(cols = 6:ncol(.), names_to = "Feature", values_to = "Area") %>%
filter(Feature %in% unique(c(unique(sig_comp[[1]]$Feature), unique(sig_comp[[2]]$Feature), unique(sig_comp[[3]]$Feature), unique(sig_comp[[4]]$Feature), unique(sig_comp[[5]]$Feature))))
rt1 <- c()
rt2 <- c()
major <- c()
minor <- c()
chem_grp <- c()
compound_name <- c()
for (row in 1:nrow(df)) {
rt1 <- c(rt1, new_df[which(new_df$Feature == as.numeric(df[row,]$Feature)),]$RT1)
rt2 <- c(rt2,new_df[which(new_df$Feature == as.numeric(df[row,]$Feature)),]$RT2)
major <- c(major, new_df[which(new_df$Feature == as.numeric(df[row,]$Feature)),]$Ion1)
minor <- c(minor, new_df[which(new_df$Feature == as.numeric(df[row,]$Feature)),]$Ion2)
chem_grp <- c(chem_grp, new_df[which(new_df$Feature == as.numeric(df[row,]$Feature)),]$Chemical_group)
}
df$RT1 <- rt1
df$RT2 <- rt2
df$Ion1 <- major
df$Ion2 <- minor
df$Chemical_group <- chem_grp
## Get compound name
compound_name <- c()
for (row in 1:nrow(df)) {
idx <- which(abs(target_comp$RT1 - df[row,]$RT1) <= 0.1 &
abs(target_comp$RT2 - df[row,]$RT2) <= 0.1 &
abs(target_comp$Ion1 - df[row,]$Ion1) <= 0.5 &
abs(target_comp$Ion2 - df[row,]$Ion2) <= 0.5)
# print(paste0(row, "_", idx))
if (identical(idx, integer(0))) {
compound_name <- c(compound_name, "unknown")
}
compound_name <- c(compound_name, target_comp[idx,]$Compound)
}
df$compound_name <- compound_name
df$Sample_name <- factor(df$Sample_name, levels = sort(unique(df$Sample_name)))
plotdf <- df %>%
filter(gas_station %in% c("Station 3", "Station 4", "Station 6", "Station 7")) %>%
filter(compound_name %notin% "unknown")
plot_list <- list()
i <- 1
for (focus_supplier in unique(plotdf$supplier)) {
plot_df <- plotdf %>%
filter(supplier %in% focus_supplier)
plot_list[[i]] <- ggplot(data = plot_df, aes(x = Sample_name, y = Area, fill = compound_name)) +
geom_bar(stat = "identity") +
labs(title = focus_supplier,
x = "",
y = "") +
theme_minimal(base_size = 18) +
theme(axis.text.x = element_text(angle = 90, hjust =0.5, vjust = 0.25,
# size = 18,
face = "bold"),
axis.ticks.length.x = unit(0, "cm"),
# legend.text = element_text(size = 18),
# legend.title = element_text(size = 18),
# axis.title.y = element_text(size = 15),
legend.position = "hidden",
plot.title = element_text(hjust = 0.5),
panel.grid.minor.x = element_blank(),
panel.grid.minor.y = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.major.y = element_blank()
) +
scale_y_continuous(expand = c(0,0), limits = c(0, 0.5))
i <- i + 1
}
legend <- cowplot::get_legend(ggplot(data = plot_df, aes(x = Sample_name, y = Area, fill = compound_name)) +
geom_bar(stat = "identity") +
facet_wrap(~supplier) +
labs(fill = "Chemical Groups") +
theme_minimal(base_size = 20) +
theme(legend.text = element_text(size = 18),
legend.title = element_text(size = 20),
axis.title.y = element_text(size = 20),
legend.position = "right"))
y <- textGrob("Peak Area", rot = 90, gp = gpar(fontsize = 20))
x <- textGrob("Samples", gp = gpar(fontsize = 20))
grid.arrange(grobs = plot_list, ncol = 2, nrow = 2, right = legend, left = y, bottom = x)
```
# Stacked bar plot of each suppliers
```{r, echo = FALSE, message = FALSE, warning = FALSE}
df <- percentage_normalized[[4]] %>% # df_step3 %>%
pivot_longer(cols = 6:ncol(.), names_to = "Feature", values_to = "Area") %>%
filter(Feature %in% unique(t_test_res$Feature))
# Obtain chemical group for each feature
# Create a named vector for fast lookup
compound_name <- setNames(t_test_res$compound_name, t_test_res$Feature)
# Use the vector to directly map the Chemical_group to the Feature in df
df$compound_name <- compound_name[df$Feature]
df$Sample_name <- factor(df$Sample_name, levels = sort(unique(df$Sample_name)))
df <- df %>%
filter(gas_station %in% c("Station 3", "Station 4", "Station 6", "Station 7")) %>%
filter(supplier %notin% "unknown") %>%
filter(Chemical_group %notin% "unknown")
plot_list <- list()
i <- 1
for (focus_supplier in unique(df$supplier)) {
plot_df <- df %>%
filter(supplier %in% focus_supplier)
plot_list[[i]] <- ggplot(data = plot_df, aes(x = Sample_name, y = Area, fill = Chemical_group)) +
geom_bar(stat = "identity") +
labs(title = focus_supplier,
x = "",
y = "") +
theme_minimal(base_size = 18) +
theme(axis.text.x = element_text(angle = 90, hjust =0.5, vjust = 0.25,
# size = 18,
face = "bold"),
axis.ticks.length.x = unit(0, "cm"),
# legend.text = element_text(size = 18),
# legend.title = element_text(size = 18),
# axis.title.y = element_text(size = 15),
legend.position = "hidden",
plot.title = element_text(hjust = 0.5),
panel.grid.minor.x = element_blank(),
panel.grid.minor.y = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.major.y = element_blank()
) +
scale_y_continuous(expand = c(0,0), limits = c(0, max(df$Area)))
i <- i + 1
}
legend <- cowplot::get_legend(ggplot(data = plot_df, aes(x = Sample_name, y = Area, fill = Chemical_group)) +
geom_bar(stat = "identity") +
facet_wrap(~supplier) +
labs(fill = "Chemical Groups") +
theme_minimal(base_size = 20) +
theme(legend.text = element_text(size = 18),
legend.title = element_text(size = 20),
axis.title.y = element_text(size = 20),
legend.position = "right"))
y <- textGrob("Peak Area", rot = 90, gp = gpar(fontsize = 20))
x <- textGrob("Samples", gp = gpar(fontsize = 20))
grid.arrange(grobs = plot_list, ncol = 3, nrow = 2, right = legend, left = y, bottom = x)
```
# Stacked bar plot of sampling seasons
```{r, echo = FALSE, message = FALSE, warning = FALSE}
df <- df_step3 %>%
pivot_longer(cols = 6:ncol(.), names_to = "Feature", values_to = "Area")
# Obtain chemical group for each feature
# Create a named vector for fast lookup
chemical_groups <- setNames(metadata$Chemical_group, metadata$Feature)
# Use the vector to directly map the Chemical_group to the Feature in df
df$Chemical_group <- chemical_groups[df$Feature]
df$Sample_name <- factor(df$Sample_name, levels = sort(unique(df$Sample_name)))
df$Octane_rating <- factor(df$Octane_rating, levels = sort(unique(df$Octane_rating)))
df$sampling_season <- factor(df$sampling_season, levels = sort(unique(df$sampling_season)))
df <- df %>% filter(supplier %notin% "unknown") %>% filter(Chemical_group %notin% "unknown")
plot_list <- list()
i <- 1
for (focus_season in levels(df$sampling_season)) {
for (focus_octane in levels(df$Octane_rating)) {
plot_df <- df %>%
filter(sampling_season %in% focus_season) %>%
filter(Octane_rating %in% focus_octane)