/
experiment3.Rmd
330 lines (265 loc) · 11.7 KB
/
experiment3.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
---
title: "Analysis of Experiment 3"
editor_options:
chunk_output_type: console
output:
workflowr::wflow_html:
code_folding: hide
---
```{r, include=FALSE}
options(width=120)
local({
hook_output <- knitr::knit_hooks$get('output')
knitr::knit_hooks$set(output = function(x, options) {
options$attr.output <- c(
options$attr.output,
sprintf('style="max-height: %s;"', options$max.height)
)
hook_output(x, options)
})
})
```
## Load data and R packages
```{r results='hide', message=F, warning=F}
# All but 1 of these packages can be easily installed from CRAN.
# However it was harder to install the showtext package. On Mac, I did this:
# installed 'homebrew' using Terminal: ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
# installed 'libpng' using Terminal: brew install libpng
# installed 'showtext' in R using: devtools::install_github("yixuan/showtext")
library(showtext)
library(brms)
library(bayesplot)
library(tidyverse)
library(gridExtra)
library(kableExtra)
library(bayestestR)
library(cowplot)
library(tidybayes)
library(scales)
library(car)
source("code/helper_functions.R")
# set up nice font for figure
nice_font <- "Lora"
font_add_google(name = nice_font, family = nice_font, regular.wt = 400, bold.wt = 700)
showtext_auto()
experiment3 <- read_csv("data/clean_data/experiment_3.csv")
expt3_counts <- experiment3 %>%
group_by(treatment, pairID, hive) %>%
summarise(n_touching = sum(touching),
n_not_touching = sum(touching== 0),
percent = n_touching / (n_touching + n_not_touching),
.groups = "drop") %>%
ungroup() %>%
filter(!is.na(n_touching)) %>%
mutate(treatment = factor(treatment, c("Ringers", "LPS"))) %>%
mutate(hive = C(factor(hive), sum)) # sum coding for hive
```
## Inspect the raw data {.tabset .tabset-fade}
### Sample sizes by treatment
```{r}
sample_sizes <- expt3_counts %>%
group_by(treatment) %>%
summarise(n = n(), .groups = "drop")
sample_sizes %>%
kable() %>% kable_styling(full_width = FALSE)
```
### Sample sizes by treatment and hive
```{r}
expt3_counts %>%
group_by(hive, treatment) %>%
summarise(n = n(), .groups = "drop") %>%
kable() %>% kable_styling(full_width = FALSE)
```
### Means and standard errors
```{r}
expt3_counts %>%
group_by(hive, treatment) %>%
summarise(pc = mean(100 * percent),
SE = sd(percent) /sqrt(n()),
n = n(), .groups = "drop") %>%
rename(`% observations in which bees were in close contact` = pc,
Hive = hive, Treatment = treatment) %>%
kable(digits = 3) %>% kable_styling(full_width = FALSE) %>%
column_spec(3, width = "2in")
```
## Histogram of the results
Note that bees more often spent close to 100% of the observation period in contact in the control group, relative to the group treated with LPS.
```{r fig.showtext = TRUE}
histo_data <- expt3_counts %>%
left_join(sample_sizes, by = "treatment") %>%
arrange(treatment)
raw_histogram <- histo_data %>%
filter(grepl("Ringers", treatment)) %>%
ggplot(aes(100 * percent,
fill = treatment)) +
geom_histogram(data = histo_data %>%
filter(grepl("LPS", treatment)),
mapping = aes(y = ..density..),
alpha = 0.5, bins = 11, colour = "black", linetype = 2) +
geom_histogram(mapping = aes(y = ..density..),
alpha = 0.5, bins = 11,
colour = "black") +
scale_fill_brewer(palette = "Set1",
direction = 1, name = "Treatment") +
xlab("% Time in close contact") + ylab("Density") +
theme_bw() +
theme(legend.position = c(0.17, 0.82),
legend.background = element_rect(fill = scales::alpha('white', 0.7)),
text = element_text(family = nice_font))
rm(histo_data)
raw_histogram
```
## Bayesian binomial model of time spent in contact
### Run the models
Fit three different binomial models, where the response is either a 0 (if bees were not in contact) or 1 (if they were).
```{r}
if(!file.exists("output/exp3_model.rds")){
prior <- c(set_prior("normal(0, 3)", class = "b"),
set_prior("normal(0, 1)", class = "sd", group = "pairID"))
exp3_model <- brm(
n_touching | trials(n) ~ treatment + hive + (1 | pairID),
data = expt3_counts %>% mutate(n = n_touching + n_not_touching),
prior = prior,
family = "binomial",
chains = 4, cores = 1, iter = 20000, seed = 1)
saveRDS(exp3_model, "output/exp3_model.rds")
}
exp3_model <- readRDS("output/exp3_model.rds")
```
### Posterior predictive check
This plot shows ten predictions from the posterior (pale blue) as well as the original data (dark blue), for the proportion of time spent in close contact (0-100%). The predicted time in contact is similar to the real data, illustrating that the model is able to recapitulate the original data fairly closely (a necessary requirement for making inferences from the model).
```{r message=F, warning=F}
pp_check(exp3_model, nsamples = 20)
```
### Fixed effects from the top model
#### Raw output of the `treatment + hive` model
```{r max.height='300px', max.width='400px'}
summary(exp3_model)
```
#### Formatted `brms` output for Table S5
The code chunk below wrangles the raw output of the `summary()` function for `brms` models into a more readable table of results, and also adds 'Bayesian p-values' (i.e. the posterior probability that the true effect size has the same sign as the reported effect).
******
***Table S5:*** Table summarising the posterior estimates of each fixed effect in the best-fitting model of Experiment 3 that contained the treatment effect. This was a binomial model where the response variable was 0 for observations in which bees were not in close contact, and 1 when they were. 'Treatment' is a fixed factor with two levels, and the effect of LPS shown here is expressed relative to the 'Ringers' treatment. 'Hive' was a fixed factor with four levels; unlike for treatment, we modelled hive using deviation coding, such that the intercept term represents the mean across all hives (in the Ringers treatment), and the three hive terms represent the deviation from this mean for three of the four hives. The model also included one random effect, 'pair ID', which grouped observations made on each pair of bees, preventing pseudoreplication. The $PP$ column gives the posterior probability that the true effect size is opposite in sign to what is reported in the Estimate column, similarly to a $p$-value.
```{r}
tableS5 <- get_fixed_effects_with_p_values(exp3_model) %>%
mutate(mu = map_chr(str_extract_all(Parameter, "mu[:digit:]"), ~ .x[1]),
Parameter = str_remove_all(Parameter, "mu[:digit:]_"),
Parameter = str_replace_all(Parameter, "treatment", "Treatment: "),
Parameter = str_replace_all(Parameter, "observation_time_minutes", "Observation duration (minutes)")) %>%
arrange(mu) %>%
select(-mu, -Rhat, -Bulk_ESS, -Tail_ESS) %>%
mutate(PP = format(round(PP, 4), nsmall = 4))
names(tableS5)[3:5] <- c("Est. Error", "Lower 95% CI", "Upper 95% CI")
saveRDS(tableS5, file = "figures/tableS5.rds")
tableS5 %>%
kable(digits = 3) %>%
kable_styling(full_width = FALSE)
```
## Plotting estimates from the model
```{r fig.height=3.2, fig.width=8.6, fig.showtext = TRUE, warning=FALSE}
new <- expt3_counts %>%
select(treatment) %>% distinct() %>%
mutate(n = 100, key = paste("V", 1:n(), sep = ""),
hive = NA)
plotting_data <- as.data.frame(
fitted(exp3_model,
newdata=new, re_formula = NA, summary = FALSE))
names(plotting_data) <- c("LPS", "Ringers")
plotting_data <- plotting_data %>% gather(treatment, percent_time_in_contact)
panel_c_colour <- "#CC79A7"
dot_plot <- plotting_data %>%
mutate(treatment = factor(treatment, c("Ringers", "LPS"))) %>%
ggplot(aes(percent_time_in_contact, treatment)) +
stat_dotsh(quantiles = 100, fill = "grey40", colour = "grey40") +
stat_pointintervalh(
mapping = aes(colour = treatment, fill = treatment),
.width = c(0.5, 0.95),
position = position_nudge(y = -0.07),
point_colour = "grey26", pch = 21, stroke = 0.4) +
xlab("Mean % time in close contact") + ylab("Treatment") +
scale_colour_brewer(palette = "Pastel1",
direction = -1, name = "Treatment") +
scale_fill_brewer(palette = "Pastel1",
direction = -1, name = "Treatment") +
theme_bw() +
coord_cartesian(ylim=c(1.4, 2.4)) +
theme(
text = element_text(family = nice_font),
strip.background = element_rect(fill = "#eff0f1"),
panel.grid.major.y = element_blank(),
legend.position = "none"
)
# positive effect = odds of this outcome are higher for trt2 than trt1 (put control as trt1)
get_log_odds <- function(trt1, trt2){
log((trt2 / (1 - trt2) / (trt1 / (1 - trt1))))
}
# LOR <- plotting_data %>%
# mutate(posterior_sample = rep(1:(n()/2), 2)) %>%
# spread(treatment, percent_time_in_contact) %>%
# mutate(LOR = get_log_odds(Ringers/100, LPS/100)) %>%
# select(LOR)
#
# LOR_plot <- LOR %>%
# ggplot(aes(LOR, y =1)) +
# geom_vline(xintercept = 0, linetype = 2) +
# stat_dotsh(quantiles = 100, fill = "grey40", colour = "grey40") +
# stat_pointintervalh(
# colour = panel_c_colour, fill = panel_c_colour,
# .width = c(0.5, 0.95),
# position = position_nudge(y = -0.1),
# point_colour = "grey26", pch = 21, stroke = 0.4) +
# coord_cartesian(ylim=c(0.86, 2)) +
# xlab("Effect of LPS on mean\n% time in close contact (LOR)") +
# ylab("Posterior density") +
# theme_bw() +
# theme(
# text = element_text(family = nice_font),
# axis.text.y = element_blank(),
# axis.ticks.y = element_blank(),
# panel.grid.major.y = element_blank(),
# panel.grid.minor.y = element_blank(),
# legend.position = "none"
# )
p <- cowplot::plot_grid(raw_histogram,
dot_plot, labels = c("A", "B"),
nrow = 1, align = 'h', axis = 'l')
ggsave(plot = p, filename = "figures/fig3.pdf", height = 3.4, width = 9)
p
```
***Figure 3:*** Results of Experiment 3 (n = 439 bees). Panel A shows the frequency distribution of the % time in close contact, for pairs of bees from the LPS treatment and the Ringers control. Panel B shows the posterior estimates of the mean % time spent in close contact; the details of the quantile dot plot and error bars are the same as described for Figure 1.
## Hypothesis testing and effect sizes
***Table S6:*** Pairs in which one bee had received LPS were observed in close contact less frequently than pairs in which one bee had received Ringers.
```{r}
get_log_odds <- function(trt1, trt2){
log((trt2 / (1 - trt2) / (trt1 / (1 - trt1))))
}
my_summary <- function(df) {
diff <- (df %>% pull(Ringers)) - (df %>% pull(LPS))
LOR <- get_log_odds((df %>% pull(Ringers))/100,
(df %>% pull(LPS))/100)
p <- 1 - (diff %>% bayestestR::p_direction() %>% as.numeric())
diff <- diff %>% posterior_summary() %>% as_tibble()
LOR <- LOR %>% posterior_summary() %>% as_tibble()
output <- rbind(diff, LOR) %>%
mutate(PP=p,
Metric = c("Absolute difference in % time in close contact",
"Log odds ratio")) %>%
select(Metric, everything()) %>%
mutate(PP = format(round(PP, 4), nsmall = 4))
output$PP[1] <- " "
output
}
tableS6 <- plotting_data %>%
as_tibble() %>%
mutate(sample = rep(1:(n() / 2), 2)) %>%
spread(treatment, percent_time_in_contact) %>%
mutate(difference = LPS - Ringers) %>%
my_summary() %>%
mutate(` ` = ifelse(PP < 0.05, "\\*", ""),
` ` = replace(` `, PP < 0.01, "**"),
` ` = replace(` `, PP < 0.001, "***"),
` ` = replace(` `, PP == " ", ""))
saveRDS(tableS6, "figures/tableS6.rds")
tableS6 %>%
kable(digits = 3) %>% kable_styling()
```