-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmeta_analysis_main_script_Revision.R
More file actions
1956 lines (1647 loc) · 85.1 KB
/
meta_analysis_main_script_Revision.R
File metadata and controls
1956 lines (1647 loc) · 85.1 KB
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
# Meta survival data analysis
# Author: Canan Karakoc
# Last update: February 22, 2024
################################################################################################
# SETUP #
################################################################################################
# Install/load libraries
# Some packages are loded in-code
library(tidyverse)
library(minpack.lm) # for regressions
library(ggforce) # for the supplementary plot
library(patchwork) # to combine plots
# Function to calculate standard error
standard_error <- function(x) {
n <- sum(!is.na(x)) # Number of non-NA observations
if (n == 0) {
return(NA)
} else {
return(sd(x, na.rm = TRUE) / sqrt(n))
}
}
set.seed(1234)
setwd("~/GitHub/metaAnalysis")
# Manuscript figures
# panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
mytheme <- theme_bw() +
theme(axis.ticks.length = unit(.25, "cm")) +
theme(legend.text = element_text(size = 14)) +
theme(axis.text = element_text(size = 14, color = "black"), axis.title = element_text(size = 16)) +
theme(panel.border = element_rect(
fill = NA, colour = "black",
size = 1
)) +
theme(strip.text.x = element_text(size = 14), strip.background = element_blank()) +
theme(legend.title = element_blank()) +
theme(panel.border = element_rect(
fill = NA, colour = "black",
linewidth = 1
)) +
theme(
axis.text.x.top = element_blank(), axis.title.x.top = element_blank(),
axis.text.y.right = element_blank(), axis.title.y.right = element_blank()
) +
theme(
axis.title.x = element_text(margin = margin(10, 0, 0)),
axis.title.y = element_text(margin = margin(0, 10, 0, 0)),
axis.text.x = element_text(margin = margin(10, 0, 0, 0)),
axis.text.y = element_text(margin = margin(0, 10, 0, 0))
)
# Color blind palette
cbpalette <- c("#0072B2", "#D55E00", "#009E73", "#CC79A7", "#56B4E9", "#999999", "#F0E442", "#000000")
# Loading data
# Data will be uploaded to Figshare - Too large for GitHub
main.dir <- "~/GitHub/metaAnalysis_largeFiles/metaData"
allFiles <- list.files(path = main.dir, recursive = TRUE, full.names = TRUE)
csv_files <- allFiles[grep("\\.csv$", allFiles)]
# Meta data for later
meta <- read.csv("~/GitHub/metaAnalysis/data/000_combined_library.csv",
sep = ",", header = T, na.strings = ""
)
###############################################################################################
# DATA CLEANING #
###############################################################################################
# Read all CSV files into a list of data frames
dataAll <- csv_files %>%
setNames(basename(csv_files)) %>%
map_df(read_csv, .id = "Full_key", col_names = c("Time", "Survival"))
# Clean the raw data before standardization
dataClean <- dataAll %>%
mutate(key = gsub("\\..*", "", Full_key)) %>%
mutate(Key = gsub("\\_.*", "", key)) %>%
dplyr::select(-key) %>%
left_join(meta, by = "Key") %>%
mutate(across(Time:Survival, ~ ifelse(.x < 0, 0, .x))) %>% # Replace negative values with 0
mutate(across(Survival, ~ ifelse(.x > 100, 100, .x)))%>% # Cap survival at 100%
mutate(Survival = round(Survival, 0)) # Counts can't be floating number
# Function to remove repeating zeros after the first occurrence of zero
remove_repeating_zeros <- function(data) {
# Check if there are any zeros in the Survival_corrected column
if (any(data$Survival_corrected == 0)) {
# Identify the first occurrence of zero in the Survival_corrected column
first_zero_index <- min(which(data$Survival_corrected == 0))
# Keep rows only up to the first occurrence of zero
return(data[1:first_zero_index, ])
} else {
# If there are no zeros, return the entire dataset
return(data)
}
}
# Function to ensure survival is always decreasing or the same over time
ensure_decreasing_survival <- function(Survival_corrected) {
# Loop through the survival values and ensure non-increasing values
for (i in 2:length(Survival_corrected)) {
if (Survival_corrected[i] > Survival_corrected[i - 1]) {
Survival_corrected[i] <- Survival_corrected[i - 1] # Set current value to the previous if it's higher
}
}
return(Survival_corrected)
}
# Reverse datasets and ensure survival decreases over time
# Filter out datasets where the last survival value is greater than 20
# Remove trailing zeros from Survival_corrected
# Find unique datasets to reverse using Reverse_Flag column
datasets_to_reverse <- dataClean %>%
filter(Graph == "mortality") %>%
pull(Full_key) %>%
unique()
dataCleanSurvival <- dataClean %>%
group_by(Full_key) %>%
group_modify(~ {
.x <- .x %>%
arrange(Time) # Always ensure the data is sorted by Time
# Reverse survival if the dataset is marked for reversal
if (.y$Full_key %in% datasets_to_reverse) {
.x <- .x %>%
mutate(Survival_corrected = 100 - Survival) # Reverse Survival for datasets needing reversal
} else {
.x <- .x %>%
mutate(Survival_corrected = Survival) # Otherwise, keep Survival unchanged
}
# Ensure the Survival values are non-increasing
.x <- .x %>%
mutate(Survival_corrected = ensure_decreasing_survival(Survival_corrected)) # Apply the non-increasing rule
return(.x)
}) %>%
ungroup() %>% # Ungroup after the group_modify operation
group_by(Full_key) %>%
filter(last(Survival_corrected) <= 20) %>%
group_modify(~ remove_repeating_zeros(.x)) %>% # Pass the whole dataframe to the function
ungroup()
# Find datasets with time unit in days
datasets_in_days <- dataCleanSurvival %>%
filter(Time_units == "days") %>%
pull(Full_key) %>%
unique()
datasets_in_weeks <- dataCleanSurvival %>%
filter(Time_units == "weeks") %>%
pull(Full_key) %>%
unique()
# Continue with the rest of your pipeline (time conversion, standardization, etc.)
dataCleanSurvival_hours <- dataCleanSurvival %>%
mutate(Time_hours = case_when(
Full_key %in% datasets_in_days ~ Time * 24, # Convert days to hours
Full_key %in% datasets_in_weeks ~ Time * 7 * 24, # Convert weeks to hours
TRUE ~ Time # If already in hours, keep as is
))
# Standardize both Survival and Time values between 0 and 1
standardized_df <- dataCleanSurvival_hours %>%
group_by(Full_key) %>%
# Check if all survival values are constant (i.e., max == min)
mutate(is_constant = max(Survival_corrected) == min(Survival_corrected)) %>%
# Apply standardization for non-constant datasets
mutate(
Standardized_Survival = ifelse(
!is_constant, # Only apply standardization when survival varies
(Survival_corrected - min(Survival_corrected)) / (max(Survival_corrected) - min(Survival_corrected)),
1 # For constant survival datasets, assign 1
),
# Standardize Time_hours between 0 and 1
Time_std = (Time_hours - min(Time_hours)) / (max(Time_hours) - min(Time_hours))
) %>%
# Ensure the last survival value is 0
mutate(Standardized_Survival = ifelse(row_number() == n(), 0, Standardized_Survival)) %>%
# Replace very small values with 0.001 to avoid zero issues (after setting last value to 0)
mutate(Standardized_Survival = ifelse(Standardized_Survival < 0.001 & Standardized_Survival != 0, 0.001, Standardized_Survival)) %>%
ungroup() %>%
dplyr::select(-is_constant) # Remove the helper column
# Final data to use
standardized_final_df <- standardized_df %>%
dplyr::select(
Full_key, Key, Time, Survival, Time_hours, Time_std, Survival_corrected, Standardized_Survival,
Host_taxa, Pathogen_taxa, Max_num_host, Data
)
# Number of datasets after filtering
unique(standardized_final_df$Full_key)
ggplot(dataCleanSurvival, aes(x = Time, y = Survival_corrected, group = Full_key)) +
geom_line() + geom_point() +
labs(title = "Survival Corrected Before Standardization")
ggplot(standardized_final_df, aes(x = Time, y = Standardized_Survival, group = Full_key)) +
geom_line() + geom_point() +
labs(title = "Standardized Survival After Cleaning")
write.csv(standardized_final_df, "data/standardized_final_df.csv", row.names = FALSE)
################################################################################################
# MODELS #
################################################################################################
# Create folders to store the plots
dir.create("exponential_model_plots", showWarnings = FALSE)
dir.create("weibull_model_plots", showWarnings = FALSE)
dir.create("gompertz_survival_model_plots", showWarnings = FALSE)
dir.create("loglogistic_model_plots", showWarnings = FALSE)
dir.create("generalizedgamma_model_plots", showWarnings = FALSE)
# Model fitting functions with explicit parameter extraction for recording
# Exponential model fitting
fit_exponential <- function(data, start_lambda = 0.1) {
message("Fitting Exponential model...")
fit <- try(nlsLM(Standardized_Survival ~ exp(-lambda * Time_std), data = data,
start = list(lambda = start_lambda), control = nls.lm.control(maxiter = 1000)), silent = FALSE)
if (inherits(fit, "try-error") || any(is.na(coef(fit)))) {
message("Exponential model fitting failed.")
return(NULL)
} else {
lambda <- coef(fit)["lambda"]
message("Exponential model fit successful.")
return(list(fit = fit, params = list(lambda = as.numeric(lambda)), rss = sum(residuals(fit)^2)))
}
}
# Weibull model fitting
fit_weibull <- function(data, start_lambda = 1, start_k = 0.1) {
message("Fitting Weibull model...")
fit <- try(nlsLM(Standardized_Survival ~ exp(-(Time_std / lambda)^k), data = data,
start = list(lambda = start_lambda, k = start_k), control = nls.lm.control(maxiter = 1000)), silent = FALSE)
if (inherits(fit, "try-error") || any(is.na(coef(fit)))) {
message("Weibull model fitting failed.")
return(NULL)
} else {
lambda <- coef(fit)["lambda"]
k <- coef(fit)["k"]
message("Weibull model fit successful.")
return(list(fit = fit, params = list(lambda = as.numeric(lambda), k = as.numeric(k)), rss = sum(residuals(fit)^2)))
}
}
# Gompertz survival model with Standardized Time
fit_gompertz_survival <- function(data, start_a = 1, start_b = 1) {
message("Fitting Gompertz Survival model (Standardized Time)...")
fit <- try(nlsLM(Standardized_Survival ~ exp(-(a / b) * (exp(b * Time_std) - 1)), data = data,
start = list(a = start_a, b = start_b),
#lower = c(a = 0, b = 0), upper = c(a = Inf, b = Inf),
control = nls.lm.control(maxiter = 1000)), silent = FALSE)
if (inherits(fit, "try-error") || any(is.na(coef(fit)))) {
message("Gompertz model fitting failed.")
return(NULL)
} else {
a <- coef(fit)["a"]
b <- coef(fit)["b"]
lt50 <- (1 / b) * log((log(2) * b / a) + 1) # LT50 calculation
message("Gompertz model fit successful.")
return(list(fit = fit, params = list(a = as.numeric(a), b = as.numeric(b)), LT50 = lt50, rss = sum(residuals(fit)^2)))
}
}
# Gompertz survival model with Raw Time (Time_hours)
fit_gompertz_survival_rawtime <- function(data, start_a = 0.005, start_b = 0.0005) {
message("Fitting Gompertz Survival model (Raw Time)...")
fit <- try(nlsLM(Standardized_Survival ~ exp(-(a / b) * (exp(b * Time_hours) - 1)), data = data,
start = list(a = start_a, b = start_b),
#lower = c(a = 0, b = 0), upper = c(a = 1, b = 1),
control = nls.lm.control(maxiter = 1000)), silent = FALSE)
if (inherits(fit, "try-error") || any(is.na(coef(fit)))) {
message("Gompertz Raw Time model fitting failed.")
return(NULL)
} else {
a <- coef(fit)["a"]
b <- coef(fit)["b"]
lt50 <- (1 / b) * log((log(2) * b / a) + 1) # LT50 calculation
message("Gompertz Raw Time model fit successful.")
return(list(fit = fit, params = list(a = as.numeric(a), b = as.numeric(b)), LT50 = lt50, rss = sum(residuals(fit)^2)))
}
}
# Log-Logistic model fitting
fit_loglogistic <- function(data, start_alpha = 1, start_beta = 1) {
message("Fitting Log-Logistic model...")
fit <- try(nlsLM(Standardized_Survival ~ 1 / (1 + (Time_std / alpha)^beta), data = data,
start = list(alpha = start_alpha, beta = start_beta),
#lower = c(alpha = 0, beta = 0), upper = c(alpha = Inf, beta = Inf),
control = nls.lm.control(maxiter = 1000)), silent = FALSE)
if (inherits(fit, "try-error") || any(is.na(coef(fit)))) {
message("Log-Logistic model fitting failed.")
return(NULL)
} else {
alpha <- coef(fit)["alpha"]
beta <- coef(fit)["beta"]
message("Log-Logistic model fit successful.")
return(list(fit = fit, params = list(alpha = as.numeric(alpha), beta = as.numeric(beta)), rss = sum(residuals(fit)^2)))
}
}
# Generalized Gamma model fitting
fit_generalizedgamma <- function(data, start_beta = 1, start_gamma = 1, start_alpha = 1) {
message("Fitting Generalized Gamma model...")
fit <- try(nlsLM(Standardized_Survival ~ exp(-(Time_std / beta)^gamma * (1 + (alpha - 1) * (Time_std / beta)^gamma)),
data = data, start = list(beta = start_beta, gamma = start_gamma, alpha = start_alpha),
#lower = c(beta = 0, gamma = 0, alpha = 0), upper = c(beta = Inf, gamma = Inf, alpha = Inf),
control = nls.lm.control(maxiter = 1000)), silent = FALSE)
if (inherits(fit, "try-error") || any(is.na(coef(fit)))) {
message("Generalized Gamma model fitting failed.")
return(NULL)
} else {
beta <- coef(fit)["beta"]
gamma <- coef(fit)["gamma"]
alpha <- coef(fit)["alpha"]
message("Generalized Gamma model fit successful.")
return(list(fit = fit, params = list(beta = as.numeric(beta), gamma = as.numeric(gamma), alpha = as.numeric(alpha)), rss = sum(residuals(fit)^2))) } }
# Function to calculate AICc
calculate_aicc <- function(model, data) {
n <- nrow(data)
k <- length(coef(model)) + 1 # number of parameters including the variance
if (n <= k + 1) {
return(Inf) # Return infinity if sample size is too small
}
aic <- AIC(model)
aicc <- aic + (2 * k * (k + 1)) / (n - k - 1)
return(aicc)
}
# Function to create and save model fit plot
save_model_fit_plot <- function(data, predictions, dataset_name, model_name, folder_name) {
# Set the x variable based on the model type
if (model_name == "gompertz_survival_rawtime") {
x_var <- data$Time_hours
x_label <- "Time (Hours)"
} else {
x_var <- data$Time_std
x_label <- "Standardized Time"
}
# Create a prediction data frame using the correct x-axis variable
prediction_df <- data.frame(x_var = seq(min(x_var), max(x_var), length.out = 100), Predictions = predictions)
# Generate the plot
plot <- ggplot() +
geom_point(data = data, aes(x = x_var, y = Standardized_Survival), color = "black", size = 3, shape = 1) +
geom_line(data = prediction_df, aes(x = x_var, y = Predictions), color = "firebrick") +
labs(title = paste(model_name, "Model Fit for Dataset:", dataset_name), x = x_label, y = "Survival") +
theme_bw()
# Create the folder and save the plot
dir.create(folder_name, showWarnings = FALSE)
plot_filename <- paste0(folder_name, "/model_fit_", dataset_name, ".png")
ggsave(filename = plot_filename, plot = plot, width = 8, height = 6)
}
# Initialize storage for results and predictions
all_results <- data.frame(Dataset = character(), Model = character(), AICc = numeric(),
lambda = numeric(), k = numeric(), a = numeric(), b = numeric(),
alpha = numeric(), beta = numeric(), gamma = numeric(), LT50 = numeric(),
Log_MT_Linearity = numeric(), Num_Obs = integer(), stringsAsFactors = FALSE)
all_predictions <- data.frame(Full_key = character(), Model = character(), Time = numeric(), Predictions = numeric())
unique_datasets <- standardized_final_df$Full_key
# Main loop to process each dataset with updated checks
for (dataset_name in unique_datasets) {
message(paste("Processing dataset:", dataset_name))
dataset <- standardized_final_df %>%
filter(Full_key == dataset_name) %>%
dplyr::select(Time_std, Standardized_Survival, Time_hours)
# Fit models and store in a list
model_fits <- list(
exponential = fit_exponential(dataset),
weibull = fit_weibull(dataset),
gompertz_survival = fit_gompertz_survival(dataset),
gompertz_survival_rawtime = fit_gompertz_survival_rawtime(dataset),
loglogistic = fit_loglogistic(dataset),
generalizedgamma = fit_generalizedgamma(dataset)
)
# Process each model
for (model_name in names(model_fits)) {
fit <- model_fits[[model_name]]
# Skip if model fit is NULL
if (is.null(fit) || is.null(fit$params)) {
message(paste("Skipping model", model_name, "for dataset", dataset_name, "due to missing parameters."))
next
}
# Extract parameters for each model to save for post-hoc analysis
params <- fit$params
lambda <- if ("lambda" %in% names(params)) as.numeric(params["lambda"]) else NA
k <- if ("k" %in% names(params)) as.numeric(params["k"]) else NA
a <- if ("a" %in% names(params)) as.numeric(params["a"]) else NA
b <- if ("b" %in% names(params)) as.numeric(params["b"]) else NA
alpha <- if ("alpha" %in% names(params)) as.numeric(params["alpha"]) else NA
beta <- if ("beta" %in% names(params)) as.numeric(params["beta"]) else NA
gamma <- if ("gamma" %in% names(params)) as.numeric(params["gamma"]) else NA
lt50 <- if (!is.null(fit$LT50)) fit$LT50 else NA
# Calculate AICc
aicc_value <- if (!is.null(fit$fit)) calculate_aicc(fit$fit, dataset) else NA
# Generate predictions for each model based on the fitted parameters
time_points <- if (model_name == "gompertz_survival_rawtime") dataset$Time_hours else dataset$Time_std
prediction_times <- seq(min(time_points), max(time_points), length.out = 100)
# Generate predictions based on the model type
if (model_name %in% c("gompertz_survival", "gompertz_survival_rawtime")) {
# Check if a and b are numeric and non-NA before calculating predictions
if (is.numeric(a) && is.numeric(b) && !is.na(a) && !is.na(b)) {
preds <- exp(-(a / b) * (exp(b * prediction_times) - 1))
} else {
message(paste("Skipping predictions for model", model_name, "in dataset", dataset_name, "due to non-numeric a or b."))
next
}
} else if (!is.null(fit$fit)) {
preds <- try(predict(fit$fit, newdata = data.frame(Time_std = prediction_times)), silent = TRUE)
if (inherits(preds, "try-error")) {
message(paste("Prediction failed for model", model_name, "in dataset", dataset_name))
next
}
} else {
next
}
# Save predictions to all_predictions dataframe
predictions <- data.frame(Full_key = dataset_name, Model = model_name, Time = prediction_times, Predictions = preds)
all_predictions <- rbind(all_predictions, predictions)
# Save plot for each model
save_model_fit_plot(dataset, preds, dataset_name, model_name, paste0(model_name, "_model_plots"))
# Save model parameters to all_results dataframe
result <- data.frame(
Dataset = dataset_name,
Model = model_name,
AICc = aicc_value,
lambda = lambda,
k = k,
a = a,
b = b,
alpha = alpha,
beta = beta,
gamma = gamma,
LT50 = lt50,
Log_MT_Linearity = NA, # Placeholder for linearity check
Num_Obs = nrow(dataset)
)
all_results <- rbind(all_results, result)
}
}
# Save all results and predictions to files
# These large files won't be pushed to GitHub
write.csv(all_results, "data/results_df.csv", row.names = FALSE)
write.csv(all_predictions, "data/all_predictions.csv", row.names = FALSE)
##############################################################################################
# READ SAVED DATA #
standardized_final_df <- read.table("data/standardized_final_df.csv", header = T, sep = ",", dec = ".")
all_results <- read.table("data/results_df.csv", header = T, sep = ",", dec = ".")
all_predictions <- read.table("data/all_predictions.csv", header = T, sep = ",", dec = ".")
#all_results <- read.table("~/GitHub/metaAnalysis_largeFiles/results_predictions/results_df.csv", header = T, sep = ",", dec = ".")
#all_predictions <- read.table("~/GitHub/metaAnalysis_largeFiles/results_predictions/all_predictions.csv", header = T, sep = ",", dec = ".")
###############################################################################################
# FIGURE 1 & FIGURE S1 #
###############################################################################################
# Create combined_factor and plotting_data
standardized_final_df$combined_factor <- interaction(standardized_final_df$Host_taxa, standardized_final_df$Pathogen_taxa, sep = "\n")
plotting_data <- standardized_final_df %>%
dplyr::select(Full_key, combined_factor, Standardized_Survival, Time_std) %>%
mutate(key = gsub("\\..*", "", Full_key))
# Create factors
factors <- standardized_final_df %>%
dplyr::select(Full_key, combined_factor)
# Merge and arrange prediction data
prediction_plotting_data <- all_predictions %>%
mutate(key = gsub("\\..*", "", Full_key)) %>%
left_join(factors, by = "Full_key") %>%
filter(!Model == "gompertz_survival_rawtime") %>%
arrange(combined_factor)
fig1_dat1 <- plotting_data %>%
filter(Full_key == "8C5XBCN2A.csv")
fig1_dat2 <- prediction_plotting_data %>%
filter(Full_key == "8C5XBCN2A.csv") %>%
filter(!Model == "gompertz_survival_rawtime")
fig1_dat2$Model <- factor(fig1_dat2$Model,
levels = c("exponential", "gompertz_survival", "weibull",
"loglogistic", "generalizedgamma"))
aic <- all_results %>% filter(Dataset == "8C5XBCN2A.csv")
fig1 <- ggplot(fig1_dat1, aes(x = Time_std, y = Standardized_Survival)) +
geom_point(size = 4, color = "grey25") + # Raw data
geom_line(data = fig1_dat2, aes(x = Time, y = Predictions, color = Model), size = 1) + # Predictions
labs(x = "Standardized time", y = "Standardized survival") +
mytheme +
theme(legend.title = element_text(size = 16))+
scale_color_manual(name = "AICc", values = cbpalette, labels = c("Constant: -1.03", "Gompertz: -27.31", "Weibull: -21.61", "Log-logistic: -12.41", "Gen.-gamma: -16.09"))+
theme(
legend.position = c(0.045, 0.045), # Positioning the legend inside the plot
legend.justification = c(0, 0) # Aligning the legend to the bottom left
)+coord_fixed(ratio = 1)
ggsave("figures/fig1.pdf", plot = fig1, width = 6.5, height = 5.5, units = "in", dpi = 300)
# Plotting - Save to model_plots folder
prediction_plotting_data <- prediction_plotting_data %>%
filter(!Model == "gompertz_survival_rawtime")
prediction_plotting_data$Model <- factor(prediction_plotting_data$Model,
levels = c("exponential", "gompertz_survival", "weibull",
"loglogistic", "generalizedgamma"))
ALL <- ggplot(plotting_data, aes(x = Time_std, y = Standardized_Survival)) +
geom_point(size = 3, color = "grey25") + # Raw data
geom_line(data = prediction_plotting_data, aes(y = Predictions, x = Time, color = Model), size = 0.7) + # Predictions
labs(x = "Standardized time", y = "Standardized survival") +
facet_wrap(~ combined_factor + key) +
scale_color_manual(values = cbpalette, labels = c("Constant","Gompertz", "Weibull", "Log-logistic", "Generalized-gamma"))+
mytheme+
theme(legend.position = "bottom")
# Pagination parameters
ncol <- 5
nrow <- 5
n_pages <- ceiling(length(unique(standardized_final_df$Full_key)) / (ncol * nrow))
# Loop to create paginated plots
for (i in 1:n_pages) {
paginated_plot <- ALL + facet_wrap_paginate(~ combined_factor + key, ncol = ncol, nrow = nrow, page = i)
# Save each page to a file
ggsave(paste0("combined_plot_page_", i, ".png"), paginated_plot, width = 16, height = 17)
# Print each paginated plot
print(paginated_plot)
}
# FIGURE 2A #
freq <- all_results %>%
distinct(Dataset, Model, .keep_all = T) %>%
group_by(Dataset) %>%
filter(AICc == min(AICc)) %>%
group_by(Model) %>%
summarise(n = n())
# Rank all models for each group by Mean_WAIC
ranked_results <- all_results %>%
filter(!Model == "<NA>") %>%
distinct(Dataset, Model, .keep_all = T) %>%
group_by(Dataset) %>%
arrange(AICc) %>%
mutate(rank = row_number()) %>%
mutate(best_model = Model[rank == 1])
# Count how many times each model ends up as the best after adjustments
model_counts <- ranked_results %>%
distinct(Dataset, .keep_all = T) %>%
group_by(best_model) %>%
summarise(n = n(), .groups = 'drop')
# Density plot for Mean_AIC by Model
# Plot with ggplot2
density2 <- ggplot(data = all_results %>% filter(Model != "gompertz_survival_rawtime") %>%
distinct(Dataset, Model, .keep_all = T), aes(x = AICc, color = Model)) +
geom_density(alpha = 0.5, size = 1) +
labs(
x = "AICc",
y = "Density") +
mytheme +
scale_color_manual(values = cbpalette, labels = c("Constant (25)", "Gompertz (70)", "Weibull (45)", "Log-logistic (61)", "Gen.-gamma (8)")) +
scale_x_continuous(limits = c(-200, 100)) +
theme(legend.position = c(0.1, 0.5),
legend.justification = c(0, 0),
legend.key = element_blank()) +
guides(color = guide_legend(override.aes = list(linetype = 1)))
# Data
# Number of host
# Some papers (marked in the meta data) have different host numbers for different trials
# I am changing them manually here.
# ASXFW6GM_1 - ASXFW6GM_4
# c(24, 18, 8, 9)
# For (SLELFBN3_1 - SLELFBN3_30)
# c(24, 28, 23, 21, 23, 27, 25, 24, 29, 29, 27, 22, 26, 27, 25, 20, 21, 26, 23, 9, 9, 10, 25, 23, 20, 15, 14, 14, 11, 12)
# FRAQNTF6_1 - FRAQNTF6_4
# c(20, 20, 19, 19)
# NSH3NLMI_1 10
# NSH3NLMI_2 12
# 72SE5ARY_1 10
# 72SE5ARY_2 20
# Sample datasets and num_hosts vectors
datasets <- c(
"ASXFW6GM_1.csv", "ASXFW6GM_2.csv", "ASXFW6GM_3.csv", "ASXFW6GM_4.csv", "SLELFBN3_1.csv", "SLELFBN3_2.csv", "SLELFBN3_3.csv", "SLELFBN3_4.csv", "SLELFBN3_5.csv",
"SLELFBN3_6.csv", "SLELFBN3_7.csv", "SLELFBN3_8.csv", "SLELFBN3_9.csv", "SLELFBN3_10.csv", "SLELFBN3_11.csv", "SLELFBN3_12.csv", "SLELFBN3_13.csv", "SLELFBN3_14.csv", "SLELFBN3_15.csv",
"SLELFBN3_16.csv", "SLELFBN3_17.csv", "SLELFBN3_18.csv", "SLELFBN3_19.csv", "SLELFBN3_20.csv", "SLELFBN3_21.csv", "SLELFBN3_22.csv", "SLELFBN3_23.csv", "SLELFBN3_24.csv", "SLELFBN3_25.csv",
"SLELFBN3_26.csv", "SLELFBN3_27.csv", "SLELFBN3_28.csv", "SLELFBN3_29.csv", "SLELFBN3_30.csv", "FRAQNTF6_1.csv", "FRAQNTF6_2.csv", "FRAQNTF6_3.csv", "FRAQNTF6_4.csv",
"NSH3NLMI_1.csv", "NSH3NLMI_2.csv", "72SE5ARY_1.csv", "72SE5ARY_2.csv"
)
num_hosts <- c(
24, 18, 8, 9, 24, 28, 23, 21, 23, 27, 25, 24, 29, 29, 27, 22, 26, 27, 25, 20, 21, 26, 23, 9, 9, 10,
25, 23, 20, 15, 14, 14, 11, 12, 20, 20, 19, 19, 10, 12, 10, 20
)
# Create mergedata data frame
mergedata <- data.frame(Dataset = datasets, Max_num_hosts = num_hosts)
allData_AIC_filled <- all_results %>%
left_join(standardized_final_df, by = c("Dataset" = "Full_key")) %>%
left_join(mergedata, by = "Dataset") %>%
mutate(Max_num_host_filled = coalesce(as.numeric(Max_num_host), as.numeric(Max_num_hosts))) %>%
dplyr::select(Dataset, Model, AICc, Num_Obs, Host_taxa, Pathogen_taxa, Data, Max_num_host_filled) %>%
distinct(Dataset, Model, .keep_all = T)
rows_with_na <- apply(allData_AIC_filled, 1, function(x) any(is.na(x)))
allData_AIC_filled[rows_with_na, ]
###############################################################################################
# FIGURE S2 & S3 #
###############################################################################################
# HOST
allData_AIC_sum <- allData_AIC_filled %>%
filter(
is.finite(as.numeric(AICc)),
is.finite(as.numeric(Num_Obs)),
is.finite(as.numeric(Max_num_host_filled))
) %>%
distinct(Dataset, Model, .keep_all = T) %>%
group_by(Model, Host_taxa) %>%
summarize(
meanAIC = mean(as.numeric(AICc), na.rm = TRUE),
sdAIC = sd(as.numeric(AICc)),
seAIC = standard_error(as.numeric(AICc)),
meanObs = round(mean(as.numeric(Num_Obs), na.rm = TRUE), 0),
meanHost = round(mean(as.numeric(Max_num_host_filled), na.rm = TRUE), 0),
numData = length(unique(Dataset))
) %>%
ungroup() %>%
filter(!Model == "gompertz_survival_rawtime")
allData_AIC_filled_clean <- allData_AIC_filled %>%
filter(
is.finite(as.numeric(AICc)),
is.finite(as.numeric(Num_Obs)),
is.finite(as.numeric(Max_num_host_filled))
) %>%
distinct(Dataset, Model, .keep_all = T) %>%
filter(!Model == "gompertz_survival_rawtime")
# Order factor levels
allData_AIC_sum$Host_taxa <- factor(allData_AIC_sum$Host_taxa,
levels = c("Seedlings", "Drosophila sp.", "Other insects",
"Nematodes", "Moth larvae", "Other invertebrates",
"Fish", "Avian", "Mice", "Other mammals"))
allData_AIC_sum$Model <- factor(allData_AIC_sum$Model,
levels = c("exponential", "gompertz_survival", "weibull",
"loglogistic", "generalizedgamma"))
# Create the plot and add the annotations
host_aic <- ggplot(allData_AIC_sum, aes(x = Model, y = meanAIC, color = Model)) +
geom_point(size = 5, shape = 21) +
geom_errorbar(aes(ymin = meanAIC - seAIC, ymax = meanAIC + seAIC), width = 0.2) +
facet_wrap(~Host_taxa, ncol = 2, scales = "free") +
mytheme +
theme(axis.text.x = element_blank(), strip.background = element_blank(), axis.title.x = element_blank()) +
ylab("AICc") +
geom_text(aes(label = paste0("num. datasets = ", numData)), x = Inf, y = Inf, hjust = 1.1, vjust = 1.2, size = 4, check_overlap = TRUE, show.legend = FALSE) +
geom_text(aes(label = paste0("num. time obs. = ", meanObs)), x = Inf, y = Inf, hjust = 1.1, vjust = 2.3, size = 4, check_overlap = TRUE, show.legend = FALSE) +
geom_text(aes(label = paste0("avg. host reps = ", meanHost)), x = Inf, y = Inf, hjust = 1.1, vjust = 3.4, size = 4, check_overlap = TRUE, show.legend = FALSE) +
theme(legend.position = "bottom") +
guides(color = guide_legend(nrow = 2, byrow = TRUE))+
scale_color_manual(values = cbpalette, labels = c("Constant", "Gompertz", "Weibull", "Log-logistic", "Gen.-gamma"))
ggsave("figures/host_aic.pdf", plot = host_aic, width = 6, height = 13, units = "in", dpi = 300)
# Stat
library(lme4)
library(lmerTest)
library(boot)
library(emmeans)
library(purrr)
library(dplyr)
cld_results_lme <- allData_AIC_filled_clean %>%
filter(!Model == "gompertz_survival_rawtime") %>%
group_by(Host_taxa) %>%
nest() %>% # Nest data by Host_taxa for grouped operations
mutate(
model = map(data, ~ lmer(AICc ~ Model + (1 | Dataset), data = .x)), # LME model with Dataset as a random effect
emms = map(model, ~ emmeans(.x, pairwise ~ Model, adjust = "Bonferroni")),
cld = map(emms, ~ cld(.x)) # Generate compact letter displays
) %>%
mutate(Host_taxa = as.character(Host_taxa)) %>% # Ensure Host_taxa is a character vector
{ set_names(.$cld, .$Host_taxa) } # Set the names of the cld list to Host_taxa
# Function to map numbers to letters, cleaning input first
number_to_letter <- function(x) {
sapply(x, function(num) {
# Clean the input: trim spaces and remove non-numeric characters
cleaned_num <- gsub("[^0-9]", "", trimws(as.character(num)))
# Split cleaned number into individual digits, map to letters, and concatenate
if (nchar(cleaned_num) > 0) {
paste0(letters[as.numeric(unlist(strsplit(cleaned_num, "")))], collapse = "")
} else {
NA # Return NA if the input is empty or invalid
}
})
}
cld_data <- cld_results_lme %>%
map_dfr(~ as.data.frame(.), .id = "Host_taxa") %>%
mutate(letters = number_to_letter(.group))
# letters are added to the main data
allData_AIC_sum_cld <- allData_AIC_sum %>%
left_join(cld_data, by = c("Host_taxa", "Model"))
# Order factor levels
allData_AIC_sum_cld$Host_taxa <- factor(allData_AIC_sum_cld$Host_taxa,
levels = c("Seedlings", "Drosophila sp.", "Other insects",
"Nematodes", "Moth larvae", "Other invertebrates",
"Fish", "Avian", "Mice", "Other mammals"))
# Create the plot and add the CLD letters
host_aic_cld <- ggplot(allData_AIC_sum_cld, aes(x = Model, y = meanAIC, color = Model)) +
geom_point(size = 5, shape = 21) +
geom_errorbar(aes(ymin = meanAIC - sdAIC, ymax = meanAIC + sdAIC), width = 0.2) +
facet_wrap(~Host_taxa, ncol = 2, scales = "free") +
mytheme +
theme(axis.text.x = element_blank(), strip.background = element_blank(), axis.title.x = element_blank()) +
ylab("AICc") +
# Add dataset and observation info
geom_text(aes(label = paste0("num. datasets = ", numData)), x = Inf, y = Inf, hjust = 1.1, vjust = 1.2, size = 4, check_overlap = TRUE, show.legend = FALSE) +
geom_text(aes(label = paste0("num. time obs. = ", meanObs)), x = Inf, y = Inf, hjust = 1.1, vjust = 2.3, size = 4, check_overlap = TRUE, show.legend = FALSE) +
geom_text(aes(label = paste0("avg. host reps = ", meanHost)), x = Inf, y = Inf, hjust = 1.1, vjust = 3.4, size = 4, check_overlap = TRUE, show.legend = FALSE) +
# Add CLD letters above error bars
geom_text(aes(label = letters, y = meanAIC + sdAIC), vjust = -0.5, size = 4, check_overlap = TRUE, show.legend = FALSE) +
# Add space at the top of each panel
scale_y_continuous(expand = expansion(mult = c(0.05, 0.5))) +
theme(legend.position = "bottom") +
guides(color = guide_legend(nrow = 2, byrow = TRUE)) +
scale_color_manual(values = cbpalette, labels = c("Constant", "Gompertz", "Weibull", "Log-logistic", "Gen.-gamma"))
ggsave("figures/host_aic_cld.pdf", plot = host_aic_cld, width = 6, height = 12, units = "in", dpi = 300)
# PATGOGEN
# Order factor levels
PallData_AIC_sum <- allData_AIC_filled %>%
filter(
is.finite(as.numeric(AICc)),
is.finite(as.numeric(Num_Obs)),
is.finite(as.numeric(Max_num_host_filled))
) %>%
distinct(Dataset, Model, .keep_all = T) %>%
group_by(Model, Pathogen_taxa) %>%
summarize(
meanAIC = mean(as.numeric(AICc)),
seAIC = standard_error(as.numeric(AICc)),
sdAIC = sd(as.numeric(AICc)),
meanObs = round(mean(as.numeric(Num_Obs)), 0),
meanHost = round(mean(as.numeric(Max_num_host_filled), na.rm = T), 0),
numData = length(unique(Dataset))
) %>%
ungroup() %>%
filter(!Model == "gompertz_survival_rawtime")
PallData_AIC_sum$Pathogen_taxa <- factor(PallData_AIC_sum$Pathogen_taxa,
levels = c("Gram-positive bacteria", "Gram-negative bacteria",
"DNA virus", "RNA virus", "Fungi", "Protozoan parasite"))
PallData_AIC_sum$Model <- factor(PallData_AIC_sum$Model,
levels = c("exponential", "gompertz_survival", "weibull",
"loglogistic", "generalizedgamma"))
# Create the plot and add the annotations
pathogen_aic <- ggplot(PallData_AIC_sum, aes(x = Model, y = meanAIC, color = Model)) +
geom_point(size = 5, shape = 21) +
geom_errorbar(aes(ymin = meanAIC - seAIC, ymax = meanAIC + seAIC), width = 0.2) +
facet_wrap(~Pathogen_taxa, ncol = 2, scales = "free") +
mytheme +
theme(axis.text.x = element_blank(), strip.background = element_blank(), axis.title.x = element_blank()) +
scale_color_manual(values = cbpalette, labels = c("Constant", "Gompertz", "Weibull", "Log-logistic", "Gen.-gamma")) +
ylab("AICc") +
geom_text(aes(label = paste0("num. datasets = ", numData)), x = Inf, y = Inf, hjust = 1.1, vjust = 1.2, size = 4, check_overlap = TRUE, show.legend = FALSE) +
geom_text(aes(label = paste0("num. time obs. = ", meanObs)), x = Inf, y = Inf, hjust = 1.1, vjust = 2.3, size = 4, check_overlap = TRUE, show.legend = FALSE) +
geom_text(aes(label = paste0("avg. host reps = ", meanHost)), x = Inf, y = Inf, hjust = 1.1, vjust = 3.4, size = 4, check_overlap = TRUE, show.legend = FALSE) +
theme(legend.position = "bottom") +
guides(color = guide_legend(nrow = 2, byrow = TRUE))
ggsave("figures/pathogen_aic.pdf", plot = pathogen_aic, width = 6, height = 8, units = "in", , dpi = 300)
# Create CLDs for AICc comparisons within each Host_taxa group
cld_results_lme_pat <- allData_AIC_filled_clean %>%
filter(!Model == "gompertz_survival_rawtime") %>%
group_by(Pathogen_taxa) %>%
nest() %>% # Nest data by Host_taxa for grouped operations
mutate(
model = map(data, ~ lmer(AICc ~ Model + (1 | Dataset), data = .x)), # LME model with Dataset as a random effect
emms = map(model, ~ emmeans(.x, pairwise ~ Model, adjust = "Bonferroni")), # Get emmeans with Kenward-Roger df correction
cld = map(emms, ~ cld(.x)) # Generate compact letter displays
) %>%
mutate(Pathogen_taxa = as.character(Pathogen_taxa)) %>% # Ensure Host_taxa is a character vector
{ set_names(.$cld, .$Pathogen_taxa) } # Set the names of the cld list to Host_taxa
cld_data_pat <- cld_results_lme_pat %>%
map_dfr(~ as.data.frame(.), .id = "Pathogen_taxa") %>%
mutate(letters = number_to_letter(.group))
# letters are added to the main data
allData_AIC_sum_cld_pat <- PallData_AIC_sum %>%
left_join(cld_data_pat, by = c("Pathogen_taxa", "Model"))
allData_AIC_sum_cld_pat$Pathogen_taxa <- factor(allData_AIC_sum_cld_pat$Pathogen_taxa,
levels = c("Gram-positive bacteria", "Gram-negative bacteria",
"DNA virus", "RNA virus", "Fungi", "Protozoan parasite"))
allData_AIC_sum_cld_pat$Model <- factor(allData_AIC_sum_cld_pat$Model,
levels = c("exponential", "gompertz_survival", "weibull",
"loglogistic", "generalizedgamma"))
test_host <- allData_AIC_sum_cld%>%
dplyr::select(Model, Host_taxa, letters)
test_pat <- allData_AIC_sum_cld_pat%>%
dplyr::select(Model, Pathogen_taxa, letters)
# Create the plot and add the CLD letters
pat_aic_cld <- ggplot(allData_AIC_sum_cld_pat, aes(x = Model, y = meanAIC, color = Model)) +
geom_point(size = 5, shape = 21) +
geom_errorbar(aes(ymin = meanAIC - sdAIC, ymax = meanAIC + sdAIC), width = 0.2) +
facet_wrap(~Pathogen_taxa, ncol = 2, scales = "free") +
mytheme +
theme(axis.text.x = element_blank(), strip.background = element_blank(), axis.title.x = element_blank()) +
ylab("AICc") +
# Add dataset and observation info
geom_text(aes(label = paste0("num. datasets = ", numData)), x = Inf, y = Inf, hjust = 1.1, vjust = 1.2, size = 4, check_overlap = TRUE, show.legend = FALSE) +
geom_text(aes(label = paste0("num. time obs. = ", meanObs)), x = Inf, y = Inf, hjust = 1.1, vjust = 2.3, size = 4, check_overlap = TRUE, show.legend = FALSE) +
geom_text(aes(label = paste0("avg. host reps = ", meanHost)), x = Inf, y = Inf, hjust = 1.1, vjust = 3.4, size = 4, check_overlap = TRUE, show.legend = FALSE) +
# Add CLD letters above error bars
geom_text(aes(label = letters, y = meanAIC + sdAIC), vjust = -0.5, size = 4, check_overlap = TRUE, show.legend = FALSE) +
# Add space at the top of each panel
scale_y_continuous(expand = expansion(mult = c(0.05, 0.5))) +
theme(legend.position = "bottom") +
guides(color = guide_legend(nrow = 2, byrow = TRUE)) +
scale_color_manual(values = cbpalette, labels = c("Constant", "Gompertz", "Weibull", "Log-logistic", "Gen.-gamma"))
ggsave("figures/pathogen_aic_cld.pdf", plot = pat_aic_cld, width = 6, height = 8, units = "in", , dpi = 30)
# Second revision boxpots with CLD #
allData_AIC_cld_new_host <- allData_AIC_filled_clean %>%
left_join(cld_data, by = c("Host_taxa", "Model")) %>%
left_join(allData_AIC_sum, by = c("Host_taxa", "Model"))
allData_AIC_cld_new$Host_taxa <- factor(allData_AIC_cld_new$Host_taxa,
levels = c("Seedlings", "Drosophila sp.", "Other insects",
"Nematodes", "Moth larvae", "Other invertebrates",
"Fish", "Avian", "Mice", "Other mammals"))
allData_AIC_cld_new$Model <- factor(allData_AIC_cld_new$Model,
levels = c("exponential", "gompertz_survival", "weibull",
"loglogistic", "generalizedgamma"))
# Summarize letters at group level
cld_summary <- allData_AIC_cld_new %>%
group_by(Host_taxa, Model) %>%
reframe(mean = mean(AICc),
max = max(AICc), letters = unique(letters))
# Plot
host_aic_all <- ggplot(allData_AIC_cld_new, aes(x = Model, y = AICc, color = Model)) +
geom_jitter(size = 2, shape = 21) +
geom_boxplot(alpha = 0.5) +
facet_wrap(~Host_taxa, ncol = 2, scales = "free") +
mytheme +
theme(axis.text.x = element_blank(), strip.background = element_blank(), axis.title.x = element_blank()) +
ylab("AICc") +
#scale_y_continuous(limits = c(-200, 100)) +
theme(legend.position = "bottom") +
guides(color = guide_legend(nrow = 2, byrow = TRUE)) +
scale_color_manual(values = cbpalette, labels = c("Constant", "Gompertz", "Weibull", "Log-logistic", "Gen.-gamma")) +
geom_text(data = cld_summary, aes(x = Model, y = max+10, label = letters),
hjust = 0, size = 4, check_overlap = TRUE, show.legend = FALSE) +
scale_y_continuous(expand = expansion(mult = c(0.05, 0.2)))
# Pathogen
allData_AIC_cld_new_pat <- allData_AIC_filled_clean %>%
left_join(cld_data_pat, by = c("Pathogen_taxa", "Model")) %>%
left_join(PallData_AIC_sum, by = c("Pathogen_taxa", "Model"))
allData_AIC_cld_new_pat$Pathogen_taxa <- factor(allData_AIC_cld_new_pat$Pathogen_taxa,
levels = c("Gram-positive bacteria", "Gram-negative bacteria",
"DNA virus", "RNA virus", "Fungi", "Protozoan parasite"))
allData_AIC_cld_new_pat$Model <- factor(allData_AIC_cld_new_pat$Model,
levels = c("exponential", "gompertz_survival", "weibull",
"loglogistic", "generalizedgamma"))
# Summarize letters at group level
cld_summary_pat <- allData_AIC_cld_new_pat %>%
group_by(Pathogen_taxa, Model) %>%
reframe(mean = mean(AICc),
max = max(AICc), letters = unique(letters))
pat_aic_all <- ggplot(allData_AIC_cld_new_pat, aes(x = Model, y = AICc, color = Model)) +
geom_jitter(size = 2, shape = 21) +
geom_boxplot(alpha = 0.5) +
facet_wrap(~Pathogen_taxa, ncol = 2, scales = "free") +
mytheme +
theme(axis.text.x = element_blank(), strip.background = element_blank(), axis.title.x = element_blank()) +
ylab("AICc") +
#scale_y_continuous(limits = c(-200, 100)) +
theme(legend.position = "bottom") +
guides(color = guide_legend(nrow = 2, byrow = TRUE)) +
scale_color_manual(values = cbpalette, labels = c("Constant", "Gompertz", "Weibull", "Log-logistic", "Gen.-gamma")) +
geom_text(data = cld_summary_pat, aes(x = Model, y = max+10, label = letters),
hjust = 0, size = 4, check_overlap = TRUE, show.legend = FALSE) +
scale_y_continuous(expand = expansion(mult = c(0.05, 0.2)))
ggsave("figures/host_aic_cld_box.pdf", plot = host_aic_all, width = 6, height = 12, units = "in", dpi = 300)
ggsave("figures/pathogen_aic_cld_box.pdf", plot = pat_aic_all, width = 6, height = 8, units = "in", , dpi = 30)
#################################################################################################
# DATA TYPE #
#################################################################################################
Data_AIC <- allData_AIC_filled %>%
filter(
is.finite(as.numeric(AICc)),
) %>%
group_by(Model, Data) %>%
summarize(meanAIC = mean(AICc, na.rm = TRUE), seAIC = standard_error(AICc)) %>%
filter(!Model == "gompertz_survival_rawtime")
Data_AIC$Model <- factor(Data_AIC$Model,
levels = c("exponential", "gompertz_survival", "weibull",
"loglogistic", "generalizedgamma"))
Datatype <- ggplot(Data_AIC, aes(x = Data, y = meanAIC, color = Model)) +
geom_point(size = 5, shape = 21, position = position_dodge(width = 0.5)) +
geom_errorbar(aes(ymin = meanAIC - seAIC, ymax = meanAIC + seAIC),
width = 0.2,
position = position_dodge(width = 0.5, preserve = "single")