-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGradientsBC.Rmd
More file actions
3023 lines (2357 loc) · 94 KB
/
Copy pathGradientsBC.Rmd
File metadata and controls
3023 lines (2357 loc) · 94 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
---
title: "Black Coucals gradients"
author: "null"
date: "2025-07-21"
output:
html_document:
toc: yes
toc_depth: '3'
df_print: paged
pdf_document:
toc: yes
toc_depth: 3
theme: journal
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
set.seed(123) # Set a specific seed value, such as 123
```
# Black coucals Bateman Gradients
This script models the reproductive and mating success of black coucals through generalized mixed effect models. It aims to obtain the Bateman gradient of females (n=120) and males (n=210) based on data collected over 15 breeding seasons. The study focused on black coucals inhabiting the Usangu wetlands of Tanzania.
Within males, two categories were identified: 2males comprised nesting males without extra-nest offspring (144 individuals); 3malesENO consisted of nesting males with extra-nest offspring (35 males) that provided care for offspring with one genetic partner and increased their reproductive success through additional mating or by siring young with their social partner in other males' nests
The script contains four generalized mixed effect models. The first model estimates the Bateman gradient of females and all male categories; the second model estimates the gradient of females and two male categories (nesting males with and without extra-nest offspring), and the third and fourth model obtains the gradients of females and males (separately) with standardized data of reproductive and mating success. Each model also calculates 95% credible intervals for effect sizes and sex and category-specific intercepts and slopes.
We also provide the calculations to obtain the sex and category-specific opportunities for selection and sexual selection as well as path coefficient testing for selection in age.
# Read the CSV file
```{r, warning=FALSE}
# Set the working directory
knitr::opts_knit$set(root.dir = "setwd(getwd())")
dataclean <- read.csv("data/blackcoucal_gradients.csv")
knitr::opts_chunk$set(message = FALSE)
```
## Loading the libraries
```{r, warning = FALSE}
library(ggplot2) # Visualizing results: Creates customizable plots using the grammar of graphics.
library(lme4) # To run the mixed model: Fits linear and generalized linear mixed-effects models.
library(arm) # Bayesian analysis: Provides tools for Bayesian modeling and diagnostics.
library(blmeco) # Checking for overdispersion in models: Includes tools for ecological and Bayesian model checks.
library(plyr) # Calculate means and SD: Simplifies data manipulation and aggregation tasks.
library(tidyverse) # Data science toolkit: Collection of packages for data manipulation and visualization.
library(gridExtra) # Arrange multiple plots: Helps arrange ggplot objects in grid layouts.
library(dplyr) # Data manipulation: Provides grammar for data operations like filter(), mutate(), etc.
library(ggtext) # Enhanced text formatting: Adds advanced text features for ggplot visualizations.
library(ggpubr) # Publication-ready plots: Simplifies creation of high-quality visualizations for publications.
library(cowplot) # Plot composition: Combines and aligns multiple ggplot objects effectively.
library(grid)
library(gt)
library(tibble) # for rownames_to_column
library(webshot2)
library(MuMIn)
```
## Set a theme for plots
```{r}
# Define a custom theme
custom_theme <- theme_classic() +
theme(
text = element_text(family = "Arial"),
# Legend
legend.text = element_text(size = 30),
legend.title = element_text(size = 30),
# legend.key.size = unit(0.7, "cm"),
# Axes
axis.text = element_text(size = 45), # tick labels
axis.title.x = element_text(size = 45), # x-axis label
axis.title.y = element_text(size = 45), # y-axis label (markdown allowed)
# Plot titles
plot.title = element_text(size = 55, face = "bold"),
plot.subtitle = element_text(size = 55),
plot.caption = element_text(size = 45))
#For plots traits and reproductive success
theme_plots <- function() {
theme_bw() +
theme(
legend.position = "none",
legend.text = element_text(size = 10),
legend.title = element_text(size = 10),
axis.text = element_text(size = 10),
axis.title = element_text(size = 10),
plot.title = element_text(color = "black", face = "bold")
)
}
```
### Description of data structure
```{r, echo=TRUE, error=FALSE}
# Assigning factors to variables
dataclean <- dataclean %>%
mutate(
ring_no_lab= as.factor(ring_no_lab),
ring_no = as.factor(ring_no),
year = as.factor(year),
sex = as.factor(sex),
age = as.factor(age),
epy = as.factor(epy),
category = as.factor(category),
totaloff = as.numeric(totaloff),
totalmates= as.numeric(totalmates),
totalnest_sum = as.numeric(totalnest_sum)
)
head(dataclean)
# Subsetting and visualizing the response variables by sex
ma <- dataclean %>% filter(sex == "male") %>% droplevels(); head(ma) #
fe<- dataclean %>% filter(sex =="female") %>% droplevels(); head(fe) #
hist(fe$totaloff)
hist(fe$totalmates)
hist(ma$totaloff)
hist(ma$totalmates)
### Detecting and visualizing repeated measures
#3 males with records in two different years
dataclean %>% filter(ring_no_lab=="*34")
dataclean %>% filter(ring_no_lab=="*38")
dataclean %>% filter(ring_no_lab=="CW15_143")
# Count unique number of females and males per category
counts <- dataclean %>%
group_by(category, sex) %>%
summarise(count = n_distinct(ring_no_lab))
# View the counts
print(counts)
```
### Calculating the overall number of offspring and sexes in black coucals
```{r}
# Total number of offspring
totaloff_sum <- sum(dataclean$totaloff)
print(totaloff_sum)
#Total number of individuals per sex
print(table(dataclean$sex)) #There are repeated measures of 3 males
```
# Table 1: Calculating the opportunity for selection in males and females (including comparisons)
````{r}
dataclean1 <- dataclean %>%
dplyr::group_by(ring_no_lab, sex, category, age) %>%
dplyr::summarise(
totaloff = mean(totaloff, na.rm = TRUE),
totalmates = mean(totalmates, na.rm = TRUE),
) %>%
dplyr::ungroup()
# Fit model
mod <- lm(totaloff ~ category, data = dataclean1)
# Simulate from the model
nsim <- 10000
bsim <- sim(mod, n.sims = nsim)
# Function to calculate I per level
compute_I <- function(y, categories) {
sapply(levels(categories), function(lvl) {
y_lvl <- y[categories == lvl]
var(y_lvl) / (mean(y_lvl)^2)
})
}
# Function to calculate mean per level
compute_mean <- function(y, categories) {
sapply(levels(categories), function(lvl) {
mean(y[categories == lvl])
})
}
# Function to calculate variance per level
compute_var <- function(y, categories) {
sapply(levels(categories), function(lvl) {
var(y[categories == lvl])
})
}
# Observed values
observed <- mod$fitted.values + mod$residuals
# Observed statistics
I_obs <- compute_I(observed, mod$model$category)
mean_obs <- compute_mean(observed, mod$model$category)
var_obs <- compute_var(observed, mod$model$category)
# Simulated I
X <- model.matrix(mod)
I_sims <- t(sapply(1:nsim, function(i) {
RS <- X %*% bsim@coef[i, ] + rnorm(nrow(X), 0, bsim@sigma[i])
compute_I(RS, mod$model$category)
}))
# 95% credible intervals
I_ci <- apply(I_sims, 2, quantile, probs = c(0.025, 0.975))
# Count number of observations per category
n_per_category <- as.numeric(table(mod$model$category))
# Count number of unique ring number per category
n_unique <- tapply(dataclean$ring_no_lab, dataclean$category, function(x) length(unique(x)))
# Combine into final table and round
result <- data.frame(
category = levels(mod$model$category),
N = as.numeric(n_unique),
mean_RS = round(mean_obs, 2),
var_RS = round(var_obs, 2),
I_obs = round(I_obs, 2),
Crl_lower = round(I_ci[1, ], 2),
Crlupper = round(I_ci[2, ], 2)
)
print(result)
#Visualize and save table
tab <- result %>%
mutate(category = recode(category,
"1females" = "Females",
"2males" = "Males without ENO",
"3malesENO" = "Males with ENO")) %>%
gt() %>%
tab_header(
title = "Black coucals (Opportunity for Selection)"
) %>%
cols_label(
category = "Category",
)
gtsave(tab, "tables/Table1_BC_OppSel.pdf")
#Estimating differences
# Names for clarity
colnames(I_sims) <- levels(mod$model$category)
# Calculate differences for each simulation
diff_female_vs_no_ENO <- I_sims[, "2males"] - I_sims[, "1females"]
diff_female_vs_with_ENO <- I_sims[, "3malesENO"] - I_sims[, "1females"]
diff_with_ENO_vs_no_ENO <- I_sims[, "2males"] - I_sims[, "3malesENO"]
# Function to summarize differences
summarize_diff <- function(diff_samples, label) {
cat("Comparison:", label, "\n")
cat(" Mean difference:", round(mean(diff_samples), 3), "\n")
cat(" 95% Crl:", round(quantile(diff_samples, probs = c(0.025, 0.975)), 3), "\n")
cat(" P(group1 > group2):", round(mean(diff_samples > 0), 3 ), "\n\n")
}
# Summarize all comparisons
summarize_diff(diff_female_vs_no_ENO, "Females vs Males without ENO")
summarize_diff(diff_female_vs_with_ENO, "Females vs Males with ENO")
summarize_diff(diff_with_ENO_vs_no_ENO, "Males with ENO vs Males without ENO")
# Capture the printed output from all three comparisons
output <- c(
capture.output(summarize_diff(diff_female_vs_no_ENO, "Females vs Males without ENO")),
capture.output(summarize_diff(diff_female_vs_with_ENO, "Females vs Males with ENO")),
capture.output(summarize_diff(diff_with_ENO_vs_no_ENO, "Males with ENO vs Males without ENO"))
)
# View what was captured (optional)
# cat(output, sep = "\n")
# Make the text output a simple gt table
tab<-tibble(Text = output) %>%
gt() %>%
tab_header(
title = "Estimated Differences in the Opportunity for Selection of Black Coucals"
)
tab
# Save as PDF
gtsave(tab, "tables/estimatediff/BC_OppSelection_differences.pdf")
````
# Table 1: Calculating the opportunity for sexual selection in males and females (including comparisons)
````{r}
# Fit model
mod <- lm(totalmates ~ category, data = dataclean1)
# Simulate from the model
nsim <- 10000
bsim <- sim(mod, n.sims = nsim)
# Function to calculate Is per level
compute_Is <- function(y, categories) {
sapply(levels(categories), function(lvl) {
y_lvl <- y[categories == lvl]
var(y_lvl) / (mean(y_lvl)^2)
})
}
# Functions to calculate mean and variance per level
compute_mean <- function(y, categories) {
sapply(levels(categories), function(lvl) mean(y[categories == lvl]))
}
compute_var <- function(y, categories) {
sapply(levels(categories), function(lvl) var(y[categories == lvl]))
}
# Observed values
observed <- mod$fitted.values + mod$residuals
# Observed statistics
Is_obs <- compute_Is(observed, mod$model$category)
mean_obs <- compute_mean(observed, mod$model$category)
var_obs <- compute_var(observed, mod$model$category)
# Simulated Is
X <- model.matrix(mod)
Is_sims <- t(sapply(1:nsim, function(i) {
MS <- X %*% bsim@coef[i, ] + rnorm(nrow(X), 0, bsim@sigma[i])
compute_Is(MS, mod$model$category)
}))
# 95% credible intervals
Is_ci <- apply(Is_sims, 2, quantile, probs = c(0.025, 0.975))
# Count number of unique ring number per category
n_unique <- tapply(dataclean$ring_no_lab, dataclean$category, function(x) length(unique(x)))
# Combine into final table and round
result <- data.frame(
category = levels(mod$model$category),
N = as.numeric(n_unique),
mean_MS = round(mean_obs, 2),
var_MS = round(var_obs, 2),
Is_obs = round(Is_obs, 2),
CI_lower = round(Is_ci[1, ], 2),
CI_upper = round(Is_ci[2, ], 2)
)
print(result)
#Visualize and save table
tab <- result %>%
mutate(category = recode(category,
"1females" = "Females",
"2males" = "Males without ENO",
"3malesENO" = "Males with ENO")) %>%
gt() %>%
tab_header(
title = "Black coucals (Opportunity for Sexual Selection)"
) %>%
cols_label(
category = "Category",
)
gtsave(tab, "tables/Table1_BC_OppSexSel.pdf")
# Names for clarity
colnames(Is_sims) <- levels(mod$model$category)
# Calculate differences for each simulation
diff_female_vs_no_ENO <- Is_sims[, "2males"] - Is_sims[, "1females"]
diff_female_vs_with_ENO <- Is_sims[, "3malesENO"] - Is_sims[, "1females"]
diff_with_ENO_vs_no_ENO <- Is_sims[, "3malesENO"] - Is_sims[, "2males"]
# Function to summarize differences
summarize_diff <- function(diff_samples, label) {
cat("Comparison:", label, "\n")
cat(" Mean difference:", round(mean(diff_samples), 3), "\n")
cat(" 95% Crl:", round(quantile(diff_samples, probs = c(0.025, 0.975)), 2), "\n")
cat(" P(group1 > group2):", round(mean(diff_samples > 0), 3), "\n\n")
}
# Summarize all comparisons
summarize_diff(diff_female_vs_no_ENO, "Females vs Males without ENO")
summarize_diff(diff_female_vs_with_ENO, "Females vs Males with ENO")
summarize_diff(diff_with_ENO_vs_no_ENO, "Males with ENO vs Males without ENO")
# Capture the printed output from all three comparisons
output <- c(
capture.output(summarize_diff(diff_female_vs_no_ENO, "Females vs Males without ENO")),
capture.output(summarize_diff(diff_female_vs_with_ENO, "Females vs Males with ENO")),
capture.output(summarize_diff(diff_with_ENO_vs_no_ENO, "Males with ENO vs Males without ENO"))
)
# View what was captured (optional)
# cat(output, sep = "\n")
# Make the text output a simple gt table
tab<-tibble(Text = output) %>%
gt() %>%
tab_header(
title = "Estimated Differences in the Opportunity for Sexual Selection of Black Coucals"
)
tab
# Save as PDF
gtsave(tab, "tables/estimatediff/BC_OppSexSelection_differences.pdf")
````
# Table1: Bateman gradients (poisson regression) (including comparisons)
```{r}
mod <- glmer(totaloff ~
totalmates * category +
(1|year) , family="poisson",
data = dataclean,
control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e5)))
MuMIn::r.squaredGLMM(mod)
summary(mod)
round(fixef(mod),3)
anova(mod)
# Set the number of simulations
nsim <- 10000
# Simulate the model 'mod' with 'nsim' iterations and store the results in 'bsim'
bsim <- sim(mod, n.sim = nsim)
# Examine the structure of the 'bsim' object
str(bsim)
# Calculate quantiles for the fixed effects (coefficients) of the model at probabilities 0.025, 0.5, and 0.975, rounded to two decimal places
round(apply(bsim@fixef,2,quantile, prob=c(0.025, 0.5, 0.975)),2)
Xmat <- model.matrix(~ totalmates * category, data = dataclean)
# Initialize container for AMEs by category across simulations
ncat <- length(levels(dataclean$category))
ame_mat <- matrix(NA, nrow = nsim, ncol = ncat)
colnames(ame_mat) <- levels(dataclean$category)
for (sim in 1:nsim) {
betas <- as.numeric(bsim@fixef[sim, ])
names(betas) <- colnames(Xmat)
betas <- betas[colnames(Xmat)]
eta <- Xmat %*% betas
mu <- exp(eta)
for (cat in levels(dataclean$category)) {
# Logical index for observations in this category
ind_cat <- dataclean$category == cat
# Interaction term name
interaction_term <- paste0("totalmates:category", cat)
# Handle baseline category with no interaction term
if (interaction_term %in% names(betas)) {
beta_interaction <- betas[interaction_term]
} else {
beta_interaction <- 0
}
# Marginal effect for observations in category
marginal_effects <- (betas["totalmates"] + beta_interaction) * mu[ind_cat]
# Store average marginal effect for this category and simulation
ame_mat[sim, cat] <- mean(marginal_effects)
}
}
# Summarize results: means and 95% CIs for each category
ame_summary <- data.frame(
category = levels(dataclean$category),
mean_ame = apply(ame_mat, 2, mean),
lower_95 = apply(ame_mat, 2, quantile, 0.025),
upper_95 = apply(ame_mat, 2, quantile, 0.975)
)
# Compute probability AME > 0 for each category
prob_positive <- apply(ame_mat, 2, function(x) mean(x > 0))
# Cap values at 0.999
prob_positive <- pmin(prob_positive, 0.999)
# Add to your summary table
ame_summary$prob_higherzero<- prob_positive
print(ame_summary)
tab<-ame_summary %>%
gt() %>%
tab_header(
title = "Bateman gradients (poisson regression) Average Marginal Effects by Category"
) %>%
fmt_number(
columns = vars(mean_ame, lower_95, upper_95),
decimals = 3
) %>%
cols_label(
category = "Category",
mean_ame = "Mean AME",
lower_95 = "Lower 95% CI",
upper_95 = "Upper 95% CI"
)
#save the table:
gtsave(tab, "tables/Table1_BC_AverageMarEffects_gradients.pdf")
# Example: pairwise differences
diff_female_vs_male_no_ENO <- ame_mat[, "1females"] - ame_mat[, "2males"]
diff_female_vs_male_with_ENO <- ame_mat[, "1females"] - ame_mat[, "3malesENO"]
diff_male_with_ENO_vs_no_ENO <- ame_mat[, "3malesENO"] - ame_mat[, "2males"]
summarize_diff <- function(diff_samples, label) {
data.frame(
Comparison = label,
Mean_Diff = mean(diff_samples),
Lower_95 = quantile(diff_samples, 0.025),
Upper_95 = quantile(diff_samples, 0.975),
Prob_Greater_Zero = mean(diff_samples > 0)
)
}
diff_summaries <- rbind(
summarize_diff(diff_female_vs_male_no_ENO, "Females vs Males without ENO"),
summarize_diff(diff_female_vs_male_with_ENO, "Females vs Males with ENO"),
summarize_diff(diff_male_with_ENO_vs_no_ENO, "Males with ENO vs Males without ENO")
)
tab_diff <- diff_summaries %>%
gt() %>%
tab_header(
title = "Bateman gradients (poisson distrib:AME) comparisons"
) %>%
fmt_number(
columns = vars(Mean_Diff, Lower_95, Upper_95, Prob_Greater_Zero),
decimals = 3
) %>%
cols_label(
Comparison = "Comparison",
Mean_Diff = "Mean Difference",
Lower_95 = "Lower 95% CI",
Upper_95 = "Upper 95% CI",
Prob_Greater_Zero = "P(>0)"
)
# Save table
gtsave(tab_diff, "tables/estimatediff/BC_bateman_gradient_poisson_differences.pdf")
```
# Table1: Bateman gradients (linear regression) (including comparisons)
````{r}
mod <- lmer(totaloff ~ totalmates * category +
(1|year),
data = dataclean,
control=lmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e5)))
summary(mod)
set.seed(123)
nsim <- 10000
bsim <- sim(mod,n.sim=nsim)
str(bsim)
round(apply(bsim@fixef,2,quantile, prob=c(0.025, 0.5, 0.975)),2)
colnames(bsim@fixef)
#Intercept females
Int_Fe<- bsim@fixef[,"(Intercept)"]
round(mean(Int_Fe),2) # -0.17
round(quantile(Int_Fe, prob=c(0.025, 0.975)),2) #-1.01 0.65
round(sum(bsim@fixef[,1]> 0) / nsim, 3) #0.339
#Slope females
Slop_Fe<- bsim@fixef[,"totalmates"]
round(mean(Slop_Fe),2) # 2.99
round(quantile(Slop_Fe, prob=c(0.025, 0.975)),2) #2.63 3.36
round(sum(bsim@fixef[,2]> 0) /nsim , 3) #0.999
#Intercept males without ENO
Int_ma_without<- bsim@fixef[,"(Intercept)"]+ bsim@fixef[, "category2males"]
round(mean(Int_ma_without),2) # 1.18
round(quantile(Int_ma_without, prob=c(0.025, 0.975)),2) #-1.38 3.77
round(sum(bsim@fixef[,1] + bsim@fixef[,3] > 0) /nsim , 3) #0.816
#Slope males without ENO
Slop_ma_without<- bsim@fixef[,"totalmates"] + bsim@fixef[,"totalmates:category2males"]
round(mean(Slop_ma_without),2) #1.67
round(quantile(Slop_ma_without, prob=c(0.025, 0.975)),2) #-0.94 4.15
round(sum(bsim@fixef[,"totalmates"]+ bsim@fixef[,"totalmates:category2males"]> 0) /nsim, 3) #0.0.907
#Intercept males with ENO
Int_ma_with<- bsim@fixef[,"(Intercept)"]+ bsim@fixef[,"category3malesENO"]
round(mean(Int_ma_with),2) # #4.50
round(quantile(Int_ma_with, prob=c(0.025, 0.975)),2) # 2.27 , 6.71
#Slope males with ENO
Slop_ma_with<- bsim@fixef[,"totalmates"] + bsim@fixef[,"totalmates:category3malesENO"]
round(mean(Slop_ma_with),2) #0.5
round(quantile(Slop_ma_with, prob=c(0.025, 0.975)),2) #-1.41, 2.07
round(sum(bsim@fixef[,"totalmates"]+ bsim@fixef[,"totalmates:category3malesENO"] > 0) /nsim, 3) #0.726
## Differences between slopes
# estimate differences between females and males of both male categories
# Bateman gradient for females (reference)
coefs <- bsim@fixef
colnames(coefs) # Check names to match correctly
female_gradient <- coefs[, "totalmates"]
# Gradient for males without EPO
male_no_ENO <- coefs[, "totalmates"] + coefs[, "totalmates:category2males"]
# Gradient for males with ENO
male_with_ENO <- coefs[, "totalmates"] + coefs[, "totalmates:category3malesENO"]
# Females vs males without ENO
diff_female_vs_no_ENO <- female_gradient - male_no_ENO
# Females vs males with ENO
diff_female_vs_with_ENO <- female_gradient - male_with_ENO
# Males with ENO vs males without ENO
diff_with_ENO_vs_no_ENO <- male_with_ENO - male_no_ENO
summarize_diff <- function(diff_samples, label) {
cat("Comparison:", label, "\n")
cat(" Mean difference:", mean(diff_samples), "\n")
cat(" 95% CI:", quantile(diff_samples, probs = c(0.025, 0.975)), "\n")
cat(" P(group1 > group2):", mean(diff_samples > 0), "\n\n")
}
# Capture the printed output from all three comparisons
output <- c(
capture.output(summarize_diff(diff_female_vs_no_ENO, "Females vs Males without ENO")),
capture.output(summarize_diff(diff_female_vs_with_ENO, "Females vs Males with ENO")),
capture.output(summarize_diff(diff_with_ENO_vs_no_ENO, "Males with ENO vs Males without ENO"))
)
# View what was captured (optional)
# cat(output, sep = "\n")
# Make the text output a simple gt table
tab<-tibble(Text = output) %>%
gt() %>%
tab_header(
title = "Estimated Differences Between Bateman gradients (linear regression) in Black Coucals",
) # Remove column label
# Save as PDF
gtsave(tab, "tables/estimatediff/BC_bateman_gradient_differences.pdf")
````
# Table1: Standardized Bateman gradients (including comparisons)
````{r}
#Scaling reproductive and mating success across sex categories
dataclean$mean_st_off_ <- dataclean$totaloff / mean(dataclean$totaloff)
dataclean$totalmates.z <-scale(dataclean$totalmates)
hist(dataclean$totalmates.z)
head(dataclean) # Display the dataset with the new variable
# Calculate mean and standard deviation
mean_val <- mean(dataclean$totalmates)
std_dev <- sd(dataclean$totalmates)
# Manually center and scale the variable
dataclean$totalmates.z <- (dataclean$totalmates - mean_val) / std_dev
head(dataclean) # Display the dataset with the new variable
# Display the original totalmates and the scaled totalmates
result <- dataclean[, c("totalmates", "totalmates.z")]
# View the result
print(result)
mod <- lmer(mean_st_off_ ~ totalmates.z *category +
(1|year),
data = dataclean,
control=lmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e5)))
mod
MuMIn::r.squaredGLMM(mod)
nsim <- 10000
bsim <- sim(mod,n.sim=nsim)
str(bsim)
round(apply(bsim@fixef,2,quantile, prob=c(0.025, 0.5, 0.975)),2)
#Slope females
Slop_Fe<- bsim@fixef[,"totalmates.z"]
round(mean(Slop_Fe),2) #0.57
round(quantile(Slop_Fe, prob=c(0.025, 0.975)),2) #0.51, 0.64
round(sum(bsim@fixef[,2]> 0) /nsim , 3) #0.999
#Slope males without ENO
Slop_ma_without<- bsim@fixef[,"totalmates.z"] + bsim@fixef[,"totalmates.z:category2males"]
round(mean(Slop_ma_without),2) #0.32
round(quantile(Slop_ma_without, prob=c(0.025, 0.975)),2) #-0.17 0.82
round(sum(bsim@fixef[,"totalmates.z"]+ bsim@fixef[,"totalmates.z:category2males"]> 0) /nsim, 3) #0.0.907
#Slope males with ENO
Slop_ma_with<- bsim@fixef[,"totalmates.z"] + bsim@fixef[,"totalmates.z:category3malesENO"]
round(mean(Slop_ma_with),2) #0.09
round(quantile(Slop_ma_with, prob=c(0.025, 0.975)),2) #-0.21, 0.40
round(sum(bsim@fixef[,"totalmates.z"]+ bsim@fixef[,"totalmates.z:category3malesENO"] > 0) /nsim, 3) #0.726
# Estimate differences between females and males of both male categories
# Bateman gradient for females (reference)
coefs <- bsim@fixef
colnames(coefs) # Check names to match correctly
female_gradient <- coefs[, "totalmates.z"]
# Gradient for males without EPO
male_no_ENO <- coefs[, "totalmates.z"] + coefs[, "totalmates.z:category2males"]
# Gradient for males with ENO
male_with_ENO <- coefs[, "totalmates.z"] + coefs[, "totalmates.z:category3malesENO"]
# Females vs males without ENO
diff_female_vs_no_ENO <- female_gradient - male_no_ENO
# Females vs males with ENO
diff_female_vs_with_ENO <- female_gradient - male_with_ENO
# Males with ENO vs males without ENO
diff_with_ENO_vs_no_ENO <- male_with_ENO - male_no_ENO
summarize_diff <- function(diff_samples, label) {
cat("Comparison:", label, "\n")
cat(" Mean difference:", mean(diff_samples), "\n")
cat(" 95% CI:", quantile(diff_samples, probs = c(0.025, 0.975)), "\n")
cat(" P(group1 > group2):", mean(diff_samples > 0), "\n\n")
}
summarize_diff(diff_female_vs_no_ENO, "Females vs Males without ENO")
summarize_diff(diff_female_vs_with_ENO, "Females vs Males with ENO")
summarize_diff(diff_with_ENO_vs_no_ENO, "Males with ENO vs Males without ENO")
# Capture the printed output from all three comparisons
output <- c(
capture.output(summarize_diff(diff_female_vs_no_ENO, "Females vs Males without ENO")),
capture.output(summarize_diff(diff_female_vs_with_ENO, "Females vs Males with ENO")),
capture.output(summarize_diff(diff_with_ENO_vs_no_ENO, "Males with ENO vs Males without ENO"))
)
# View what was captured (optional)
# cat(output, sep = "\n")
# Make the text output a simple gt table
tab<-tibble(Text = output) %>%
gt() %>%
tab_header(
title = "Estimated Differences Between Standardized Slopes in Black Coucals",
subtitle = "Bateman Gradient Comparisons"
)
tab
# Save as PDF
gtsave(tab, "tables/estimatediff/BC_bateman_gradient_stand_differences.pdf")
````
# Table 1: Standardized bateman gradient values (linear regression by sex) MALES
```{r}
ma_om <- ma%>%
mutate(
totalmates.z= totalmates / mean(totalmates),
mean_st_off_ = totaloff / mean(totaloff)
)
mod <- lmer(mean_st_off_ ~ totalmates.z *category +
(1|year),
data = ma_om,
control=lmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e5)))
nsim <- 10000
bsim <- sim(mod,n.sim=nsim)
str(bsim)
Slop_ma_without <- bsim@fixef[, "totalmates.z"]
round(sum(Slop_ma_without > 0) / nsim, 3)
round(mean(Slop_ma_without), 2) #0.55
round(quantile(Slop_ma_without, c(0.025, 0.975)), 2) #-0.03 1.13
Slop_ma_3malesENO <- bsim@fixef[, "totalmates.z"] + bsim@fixef[, "totalmates.z:category3malesENO"]
round(mean(Slop_ma_3malesENO), 2) #0.13
round(quantile(Slop_ma_3malesENO, c(0.025, 0.975)), 2) #-0.23 0.47
round(sum(Slop_ma_3malesENO > 0) / nsim, 3) #0.751
```
# Table 1: Standardized bateman gradient values (linear regression by sex) FEMALES
```{r}
fe <- fe %>%
mutate(
totalmates.z= totalmates / mean(totalmates),
mean_st_off_ = totaloff / mean(totaloff)
)
mod <- lmer(mean_st_off_~
totalmates.z +
(1|year),
data = fe)
nsim <- 10000
bsim <- sim(mod,n.sim=nsim)
str(bsim)
Slop_females <- bsim@fixef[, "totalmates.z"]
round(sum(Slop_females > 0) / nsim, 3)
round(mean(Slop_females ), 2) #0.
round(quantile(Slop_females , c(0.025, 0.975)), 2) #
```
#Table 2. Path coefficients age females
```{r}
fedat<- dataclean %>%
filter(sex=="female")%>% droplevels()
fedat$age <- as.numeric(fedat$age)
fedat<- fedat %>%
filter(!is.na(age))
#Path selection
# ============================
# Assign Variables
# ============================
# Trait variance standardized and relative reproductive/mating success
fedat <- fedat %>%
mutate(
Z = (age - mean(age)) / sd(age),
M = totalmates / mean(totalmates),
R = totaloff / mean(totaloff)
)
t.poly<- poly(fedat$Z,2)
fedat$Z.l<-t.poly[,1] #linear term for age
fedat$Z.q<-t.poly[,2] #quadratic term for age
# ============================
# Set variables
# ============================
#fedat$Z.l <- fedat$Z.l
Z.l <- fedat$Z.l
#fedat$Z.q <- fedat$age.q
Z.q <- fedat$Z.q
M <- fedat$M
R <- fedat$R
# ============================
# Path Coefficients
# ============================
# ---- Mating gradient on Z ----
betaMZraw <- summary(glm(M ~ Z.l +Z.q))$coefficients["Z.q", 1]
mod <- lm(M ~ Z.l +Z.q, data = fedat)
bsim <- sim(mod, n.sims = 10000)
beta_sims <- bsim@coef[, "Z.q"]
set.seed(123)
# Set the number of simulations
nsim <- 10000
# Simulate the model 'mod' with 'nsim' iterations and store the results in 'bsim'
bsim <- sim(mod, n.sim = nsim)
# Examine the structure of the 'bsim' object
str(bsim)
# Calculate quantiles for the fixed effects (coefficients) of the model at probabilities 0.025, 0.5, and 0.975, rounded to two decimal places
round(apply(bsim@coef,2,quantile, prob=c(0.025, 0.5, 0.975)),2)
#Meaning: a meaningful negative quadratic coefficient means that the relationship between age and mating success is concave down: mating success peaks at intermediate agges and declines for both younger and older individuals. ie. mid aged individuals achieve the highest mating success, selection is favouring intermediate ages
(beta_summary1 <- data.frame(
Component = "Quadratic (Z.q)",
Parameter = "Selection on Z controlling for M",
Mean = round(mean(beta_sims), 2),#strongly negative quadratic effect
lowerCrl = round(as.numeric(quantile(beta_sims, 0.025)), 2), # remove 2.5% label
upperCrl = round(as.numeric(quantile(beta_sims, 0.975)), 2),#entire interval is below zero - the negative curvature is statistically supported
P_prob = format(
round(pmin(mean(beta_sims > 0), 0.999), 3), # cap at 0.999
nsmall = 3
)#only 1.1% of simulated beta values are positive, so there is a 99% prob that the effect is negative (quadratic effect)
))
# ---- Selection gradient on Z controlling for M ----
betaRZraw <- summary(glm(R ~ Z.l +Z.q + M))$coefficients["Z.q", 1]
mod <- lm(R ~ Z.l +Z.q + M , data = fedat)
bsim <- sim(mod, n.sims = 10000)
beta_sims <- bsim@coef[, "Z.q"]
# Create data frame of output
(beta_summary2 <- data.frame(
Component = "Quadratic (Z.q)",
Parameter = "Selection gradient on Z controlling for M",
Mean = round(mean(beta_sims), 2),
lowerCrl = round(as.numeric(quantile(beta_sims, 0.025)), 2), # remove 2.5% label
upperCrl = round(as.numeric(quantile(beta_sims, 0.975)), 2),
P_prob = format(
round(pmin(mean(beta_sims > 0), 0.999), 3), # cap at 0.999
nsmall = 3
)
))
# ---- Simple Bateman gradient ----
betassraw <- summary(glm(R ~ M))$coefficients["M", 1]
mod <- lm(R ~ M, data = fedat)
bsim <- sim(mod, n.sims = 10000)
beta_sims <- bsim@coef[, "M"]
# Create data frame of output
(beta_summary3 <- data.frame(
Component = "-",
Parameter = "Simple Bateman gradient",
Mean = round(mean(beta_sims), 2),
lowerCrl = round(as.numeric(quantile(beta_sims, 0.025)), 2), # remove 2.5% label
upperCrl = round(as.numeric(quantile(beta_sims, 0.975)), 2),
P_prob = format(
round(pmin(mean(beta_sims > 0), 0.999), 3), # cap at 0.999
nsmall = 3
)
)
)
# ---- Partial Bateman gradient ----
betaRMraw <- summary(glm(R ~Z.l +Z.q + M))$coefficients["Z.q", 1]
mod <- lm(R ~ Z.l +Z.q + M , data = fedat)
bsim <- sim(mod, n.sims = 1000)
beta_sims <- bsim@coef[, "M"]
# Create data frame of output
(beta_summary4 <- data.frame(
Component = "-",
Parameter = "Partial Bateman gradient",
Mean = round(mean(beta_sims), 2),
lowerCrl = round(as.numeric(quantile(beta_sims, 0.025)), 2), # remove 2.5% label
upperCrl = round(as.numeric(quantile(beta_sims, 0.975)), 2),
P_prob = format(
round(pmin(mean(beta_sims > 0), 0.999), 3), # cap at 0.999
nsmall = 3
)
)
)
# ============================================================
# Fit models for path analysis with Z.l and Z.q
# ============================================================
# Base (raw) coefficients
betaRMraw <- summary(glm(R ~ Z.l + Z.q + M, data = fedat))$coefficients["M", 1]
# For mating gradient (M ~ Z)
betaMZlraw <- summary(glm(M ~ Z.l + Z.q, data = fedat))$coefficients["Z.l", 1]
betaMZqraw <- summary(glm(M ~ Z.l + Z.q, data = fedat))$coefficients["Z.q", 1]
betaMZraw <- sum(summary(glm(M ~ Z.l + Z.q, data = fedat))$coefficients[c("Z.l", "Z.q"), 1])
# For selection gradient (R ~ Z + M)