File size: 27,559 Bytes
2f8aa81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#model fitting: Informativity predicted by social effects on top of random phylogenetic and spatial factors

#Script was written by Sam Passmore and modified by Olena Shcherbakova

source("requirements.R")

source("install_and_load_INLA.R")

source("set_up_inla.R")

metrics_joined <- metrics_joined %>% 
  filter(!is.na(L1_log10_st)) %>%
  rename(L1_log_st = L1_log10_st) %>%
  mutate(L1_copy = L1_log_st) %>%
  filter(!is.na(L2_prop)) %>%
  mutate(L2_copy = L2_prop) %>%
  filter(!is.na(neighboring_languages_st)) %>%
  filter(!is.na(Official)) %>%
  filter(!is.na(Education)) %>%
  filter(!is.na(boundness_st)) %>%
  filter(!is.na(informativity_st))

#dropping tips not in Grambank
metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ]
tree <- keep.tip(tree, metrics_joined$Language_ID)

x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match")

## Building standardized phylogenetic precision matrix
tree_scaled <- tree

tree_vcv = vcv.phylo(tree_scaled)
typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv))))

#We opt for a sparse phylogenetic precision matrix (i.e. it is quantified using all nodes and tips), since sparse matrices make the analysis in INLA less time-intensive
tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance
phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled,
                                     nodes = "ALL",
                                     scale = FALSE)$Ainv

metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),]

#"local" set of parameters
## Create spatial covariance matrix using the matern covariance function
spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], 
                                     cov.pars = phi_1, kappa = kappa)$varcov
# Calculate and standardize by the typical variance
typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1))))
spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1
spatial_prec_mat_1 = solve(spatial_cov_std_1)
dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID)

## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix
phy_id = match(tree$tip.label, rownames(phylo_prec_mat))
metrics_joined$phy_id = phy_id

## Other effects are in the same order they appear in the dataset
metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1)

#Preparing the formulas for 10 competing models to be used in inla() call
listcombo <- list( 
  c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "L1_log_st"), 
  
  c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)"), 
  
  c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "L2_prop"), 
  
  c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"),
  
  c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"),
  
  c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "L1_log_st", "L2_prop"), 
  
  c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "L1_log10:L2_prop"),
  
  c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)",  "neighboring_languages_st"), 
  
  c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "Official"),
  
  c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "Education"))


predterms <- lapply(listcombo, function(x) paste(x, collapse="+"))

predterms <- t(as.data.frame(predterms))

predterms_short <- predterms
predterms_short <- gsub("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "Phylogenetic", predterms_short, fixed=TRUE)
predterms_short <- gsub("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "Spatial: local", predterms_short, fixed=TRUE)

predterms_short <- gsub("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "L1 speakers (nonlinear)", predterms_short, fixed=TRUE)
predterms_short <- gsub("L1_log_st", "L1 speakers (linear)", predterms_short, fixed=TRUE)
predterms_short <- gsub("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)", "L2 proportion (nonlinear)", predterms_short, fixed=TRUE)
predterms_short <- gsub("L2_prop", "L2 proportion (linear)", predterms_short, fixed=TRUE)
predterms_short <- gsub("neighboring_languages_st", "Neighbours", predterms_short, fixed=TRUE)


phylogenetic_element <- data.frame("judgement" = grepl("Phylogenetic", predterms_short),
                                   number = 1:length(predterms_short))
phylogenetic_element <- phylogenetic_element[phylogenetic_element$judgement == TRUE,]$number

spatial_element_local <- data.frame("judgement" = grepl("local", predterms_short),
                                    number = 1:length(predterms_short))
spatial_element_local <- spatial_element_local[spatial_element_local$judgement == TRUE,]$number

spatial_element_regional <- data.frame("judgement" = grepl("regional", predterms_short),
                                       number = 1:length(predterms_short))
spatial_element_regional <- spatial_element_regional[spatial_element_regional$judgement == TRUE,]$number

spatial_element <- c(spatial_element_local, spatial_element_regional)

L1_element <- data.frame("judgement" = grepl("L1 speakers (linear)", predterms_short, fixed=TRUE),
                         number = 1:length(predterms_short))
L1_element <- L1_element[L1_element$judgement == TRUE,]$number


L1_nl_element <- data.frame("judgement" = grepl("L1 speakers (nonlinear)", predterms_short, fixed=TRUE),
                            number = 1:length(predterms_short))
L1_nl_element <- L1_nl_element[L1_nl_element$judgement == TRUE,]$number

L2_prop_element <- data.frame("judgement" = grepl("L2 proportion (linear)", predterms_short, fixed=TRUE),
                              number = 1:length(predterms_short))
L2_prop_element <- L2_prop_element[L2_prop_element$judgement == TRUE,]$number
L2_prop_element <- L2_prop_element[-length(L2_prop_element)] #making sure that the interaction term (introduced below) is not treated as belonging to this isolated element

L2_prop_nl_element <- data.frame("judgement" = grepl("L2 proportion (nonlinear)", predterms_short, fixed=TRUE),
                                 number = 1:length(predterms_short))
L2_prop_nl_element <- L2_prop_nl_element[L2_prop_nl_element$judgement == TRUE,]$number

#can use only part of the interaction term within grepl() function
interaction_element <- data.frame("judgement" = grepl(":L2 proportion", predterms_short),
                                  number = 1:length(predterms_short))
interaction_element <- interaction_element[interaction_element$judgement == TRUE,]$number

neighbour_element <- data.frame("judgement" = grepl("Neighbours", predterms_short),
                                number = 1:length(predterms_short))
neighbour_element <- neighbour_element[neighbour_element$judgement == TRUE,]$number

official_element <- data.frame("judgement" = grepl("Official", predterms_short),
                               number = 1:length(predterms_short))
official_element <- official_element[official_element$judgement == TRUE,]$number

education_element <- data.frame("judgement" = grepl("Education", predterms_short),
                                number = 1:length(predterms_short))
education_element <- education_element[education_element$judgement == TRUE,]$number



#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value
phy_effects_matrix <- matrix(NA, 10, 5)
colnames(phy_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC")
spa_effects_matrix <- matrix(NA, 10, 5)
colnames(spa_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC")

intercept_matrix <- matrix(NA, 10, 5)
colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC")

social_effects_matrix_L1 <- matrix(NA, 10, 5)
colnames(social_effects_matrix_L1) <- c("2.5%", "50%", "97.5%", "model", "WAIC")
social_effects_matrix_L1_nl <- matrix(NA, 10, 5)
colnames(social_effects_matrix_L1_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC")
social_effects_matrix_L2_prop <- matrix(NA, 10, 5)
colnames(social_effects_matrix_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC")
social_effects_matrix_L2_prop_nl <- matrix(NA, 10, 5)
colnames(social_effects_matrix_L2_prop_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC")
social_effects_matrix_N <- matrix(NA, 10, 5)
colnames(social_effects_matrix_N) <- c("2.5%", "50%", "97.5%", "model", "WAIC")
social_effects_matrix_O <- matrix(NA, 10, 5)
colnames(social_effects_matrix_O) <- c("2.5%", "50%", "97.5%", "model", "WAIC")
social_effects_matrix_E <- matrix(NA, 10, 5)
colnames(social_effects_matrix_E) <- c("2.5%", "50%", "97.5%", "model", "WAIC")
social_effects_matrix_L1_L2_prop <- matrix(NA, 10, 5)
colnames(social_effects_matrix_L1_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC")

#fitted values
fitted_list <- vector("list", 10)
names(fitted_list) <- predterms_short

#marginals of hyperparameters
marginals_hyperpar_list_gaussian <- vector("list", 10)
names(marginals_hyperpar_list_gaussian) <- predterms_short

marginals_hyperpar_list_phy <- vector("list", 10)
names(marginals_hyperpar_list_phy) <- predterms_short

marginals_hyperpar_list_spa <- vector("list", 10)
names(marginals_hyperpar_list_spa) <- predterms_short

marginals_hyperpar_list_social_L1_nl <- vector("list", 10)
names(marginals_hyperpar_list_social_L1_nl) <- predterms_short

marginals_hyperpar_list_social_L2_prop_nl <- vector("list", 10)
names(marginals_hyperpar_list_social_L2_prop_nl) <- predterms_short


#marginals of fixed effects
marginals_fixed_list_Intercept <- vector("list", 10)
names(marginals_fixed_list_Intercept) <- predterms_short

marginals_fixed_list_L1 <- vector("list", 10)
names(marginals_fixed_list_L1) <- predterms_short

marginals_fixed_list_L2_prop <- vector("list", 10)
names(marginals_fixed_list_L2_prop) <- predterms_short

marginals_fixed_list_O <- vector("list", 10)
names(marginals_fixed_list_O) <- predterms_short

marginals_fixed_list_N <- vector("list", 10)
names(marginals_fixed_list_N) <- predterms_short

marginals_fixed_list_E <- vector("list", 10)
names(marginals_fixed_list_E) <- predterms_short

marginals_fixed_list_L1_L2_prop <- vector("list", 10)
names(marginals_fixed_list_L1_L2_prop) <- predterms_short




#summary statistics of random effects
summary_random_list_phy <- vector("list", 10)
names(summary_random_list_phy) <- predterms_short

summary_random_list_spa <- vector("list", 10)
names(summary_random_list_spa) <- predterms_short

summary_random_list_social_L1_nl <- vector("list", 10)
names(summary_random_list_social_L1_nl) <- predterms_short

summary_random_list_social_L2_prop_nl <- vector("list", 10)
names(summary_random_list_social_L2_prop_nl) <- predterms_short


coefm <- matrix(NA,10,1)
result <- vector("list",10)

for(i in 1:10){
  formula <- as.formula(paste("informativity_st ~ ",predterms[[i]]))
  result[[i]] <- inla(formula, family="gaussian", 
                      control.family = list(hyper = pcprior_hyper), 
                      #control.inla = list(tolerance = 1e-8, h = 0.0001), 
                      #tolerance: the tolerance for the optimisation of the hyperparameters
                      #h: the step-length for the gradient calculations for the hyperparameters.
                      data=metrics_joined, control.compute=list(waic=TRUE)) 
  
  coefm[i,1] <- round(result[[i]]$waic$waic, 2)
  
  intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) 
  intercept_matrix[i, 4] <- predterms_short[[i]]
  intercept_matrix[i, 5] <- result[[i]]$waic$waic
  
  marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]]))
  colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept")
  
  if(i %in% phylogenetic_element) {
    phy_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x),
                                                 result[[i]]$marginals.hyperpar$`Precision for phy_id`,
                                                 method = "linear") %>%
      inla.qmarginal(c(0.025, 0.5, 0.975), .)
    phy_effects_matrix[i, 4] <- predterms_short[[i]]
    phy_effects_matrix[i, 5] <- result[[i]]$waic$waic
  } 
  
  if(i %in% spatial_element) {
    spa_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x),
                                                 result[[i]]$marginals.hyperpar$`Precision for sp_id`,
                                                 method = "linear") %>%
      inla.qmarginal(c(0.025, 0.5, 0.975), .)
    spa_effects_matrix[i, 4] <- predterms_short[[i]]
    spa_effects_matrix[i, 5] <- result[[i]]$waic$waic
  }
  
  
  if(i %in% L1_nl_element){
    social_effects_matrix_L1_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x),
                                                          result[[i]]$marginals.hyperpar$`Precision for inla.group(L1_copy)`,
                                                          method = "linear") %>%
      inla.qmarginal(c(0.025, 0.5, 0.975), .)
    social_effects_matrix_L1_nl[i, 4] <- predterms_short[[i]]
    social_effects_matrix_L1_nl[i, 5] <- result[[i]]$waic$waic
  } 
  
  if(i %in% L2_prop_nl_element){
    social_effects_matrix_L2_prop_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x),
                                                               result[[i]]$marginals.hyperpar$`Precision for inla.group(L2_copy)`,
                                                               method = "linear") %>%
      inla.qmarginal(c(0.025, 0.5, 0.975), .)
    social_effects_matrix_L2_prop_nl[i, 4] <- predterms_short[[i]]
    social_effects_matrix_L2_prop_nl[i, 5] <- result[[i]]$waic$waic
  } 
  
  if(i %in% L1_element) {
    social_effects_matrix_L1[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log_st",]$`0.025quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.5quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.975quant`)
    social_effects_matrix_L1[i, 4] <- predterms_short[[i]]
    social_effects_matrix_L1[i, 5] <- result[[i]]$waic$waic
    
    marginals_fixed_list_L1[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log_st"]]))
    colnames(marginals_fixed_list_L1[[i]]) <- c("x for L1", "y for L1")
  }
  
  if(i %in% L2_prop_element) {
    social_effects_matrix_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L2_prop",]$`0.975quant`)
    social_effects_matrix_L2_prop[i, 4] <- predterms_short[[i]]
    social_effects_matrix_L2_prop[i, 5] <- result[[i]]$waic$waic
    
    marginals_fixed_list_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L2_prop"]]))
    colnames(marginals_fixed_list_L2_prop[[i]]) <- c("x for L2 proportion", "y for L2 proportion")
  }
  
  if(i %in% interaction_element) {
    social_effects_matrix_L1_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.975quant`)
    social_effects_matrix_L1_L2_prop[i, 4] <- predterms_short[[i]]
    social_effects_matrix_L1_L2_prop[i, 5] <- result[[i]]$waic$waic
    
    marginals_fixed_list_L1_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log10:L2_prop"]]))
    colnames(marginals_fixed_list_L1_L2_prop[[i]]) <- c("x for L1*L2 proportion", "y for L1*L2 proportion")
  }
  
  if(i %in% neighbour_element) {
    social_effects_matrix_N[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`)
    social_effects_matrix_N[i, 4] <- predterms_short[[i]]
    social_effects_matrix_N[i, 5] <- result[[i]]$waic$waic
    
    marginals_fixed_list_N[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]]))
    colnames(marginals_fixed_list_N[[i]]) <- c("x for Neighbours", "y for Neighbours")
  }
  
  if(i %in% official_element) {
    social_effects_matrix_O[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`)
    social_effects_matrix_O[i, 4] <- predterms_short[[i]]
    social_effects_matrix_O[i, 5] <- result[[i]]$waic$waic
    
    marginals_fixed_list_O[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]]))
    colnames(marginals_fixed_list_O[[i]]) <- c("x for Official", "y for Official")
  }
  
  if(i %in% education_element) {
    social_effects_matrix_E[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`)
    social_effects_matrix_E[i, 4] <- predterms_short[[i]]
    social_effects_matrix_E[i, 5] <- result[[i]]$waic$waic
    
    marginals_fixed_list_E[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]]))
    colnames(marginals_fixed_list_E[[i]]) <- c("x for Education", "y for Education")
  }
  
  fitted_list[[i]] <- result[[i]]$summary.fitted.values
  fitted_list[[i]] <- fitted_list[[i]] %>%
    mutate(across(where(is.numeric), round, 2))
  
  marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]]))
  colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations")
  
  if(i %in% phylogenetic_element){
    marginals_hyperpar_list_phy[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for phy_id"]]))
    colnames(marginals_hyperpar_list_phy[[i]]) <- c("x for phy_id", "y for phy_id")
  }
  
  if(i %in% spatial_element){
    marginals_hyperpar_list_spa[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for sp_id"]]))
    colnames(marginals_hyperpar_list_spa[[i]]) <- c("x for sp_id", "y for sp_id")
  }
  
  if(i %in% L1_nl_element){
    marginals_hyperpar_list_social_L1_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L1_copy)"]]))
    colnames(marginals_hyperpar_list_social_L1_nl[[i]]) <- c("x for inla.group(L1_copy)", "y for inla.group(L1_copy)")
  }
  
  if(i %in% L2_prop_nl_element){
    marginals_hyperpar_list_social_L2_prop_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L2_copy)"]]))
    colnames(marginals_hyperpar_list_social_L2_prop_nl[[i]]) <- c("x for inla.group(L2_copy)", "y for inla.group(L2_copy)")
  }
  
  if(i %in% phylogenetic_element){
    summary_random_list_phy[[i]] <- cbind(result[[i]]$summary.random$phy_id) %>%
      rename(phy_id = ID) %>%
      as.data.frame() %>%
      mutate(across(where(is.numeric), round, 2))
  }
  
  if(i %in% spatial_element){
    summary_random_list_spa[[i]] <- cbind(result[[i]]$summary.random$sp_id) %>%
      rename(sp_id = ID) %>%
      as.data.frame() %>%
      mutate(across(where(is.numeric), round, 2))
  }
}

#beepr::beep(5)

save(result, file = "output_models/models_Informativity_social.RData")


coefm <- as.data.frame(cbind(predterms_short, coefm))
colnames(coefm) <- c("model", "WAIC")
coefm <- coefm %>%
  mutate(across(.cols=2, as.numeric)) %>%
  mutate(across(where(is.numeric), round, 2)) %>%
  arrange(WAIC)

coefm$WAIC <- as.numeric(coefm$WAIC)
coefm <- coefm[order(coefm$WAIC),]

coefm_path <- paste("output_tables/", "waics", "Informativity_social_models", ".csv", collapse = "")
write.csv(coefm, coefm_path, row.names=FALSE)

for (i in 1:length(fitted_list)) {
  fitted_list[[i]]$model <- names(fitted_list)[i]
}
fitted_list <- dplyr::bind_rows(fitted_list)
fitted_list_path <- paste("output_tables/", "fitted_list", "Informativity_social_models", ".csv", collapse = "")
write.csv(fitted_list, fitted_list_path) 

phy_effects<-as.data.frame(phy_effects_matrix)
spa_effects<-as.data.frame(spa_effects_matrix)
intercept_effects <- as.data.frame(intercept_matrix)
L1_effects <- as.data.frame(social_effects_matrix_L1)
L1_nl_effects <- as.data.frame(social_effects_matrix_L1_nl)
L2_prop_effects <- as.data.frame(social_effects_matrix_L2_prop)
L2_prop_nl_effects <- as.data.frame(social_effects_matrix_L2_prop_nl)
N_effects<-as.data.frame(social_effects_matrix_N)
E_effects<-as.data.frame(social_effects_matrix_E)
O_effects<-as.data.frame(social_effects_matrix_O)
interaction_effects <- as.data.frame(social_effects_matrix_L1_L2_prop)

phy_effects$effect <- "phylogenetic SD"
spa_effects$effect <- "spatial SD"
intercept_effects$effect <- "Intercept"
L1_effects$effect <- "L1"
L1_nl_effects$effect <- "social SD:\nL1"
L2_prop_effects$effect <- "L2 proportion"
L2_prop_nl_effects$effect <- "social SD:\nL2 proportion"
N_effects$effect <- "Neighbours"
E_effects$effect <- "Education"
O_effects$effect <- "Official status"
interaction_effects$effect <- "L1*L2 proportion"

effs <- as.data.frame(rbind(phy_effects, spa_effects, intercept_effects, L1_effects, L1_nl_effects, L2_prop_effects, L2_prop_nl_effects, N_effects, O_effects, E_effects, interaction_effects))
effs <- effs %>%
  mutate(across(.cols=c(1:3, 5), as.numeric)) %>%
  mutate(across(where(is.numeric), round, 2)) %>%
  na.omit() %>%
  arrange(WAIC) %>%
  relocate(model)

effs_path <- paste("output_tables/", "effects", "Informativity_social_models", ".csv", collapse = "")
write.csv(effs, effs_path, row.names=FALSE)

effs <- read.csv("output_tables/ effects Informativity_social_models .csv")

effs_table_Main <- effs %>%
  rename("2.5%"=2,
         "50%" = 3,
         "97.5%" = 4) %>%
  filter(!grepl("nonlinear", model))

effs_table_Main$model <- gsub("(\\s*\\(\\w+\\))", "", effs_table_Main$model)

effs_table_Main <- effs_table_Main %>%
  relocate(effect, .after = model) %>%
  flextable() %>%
  flextable::bold(~ (`2.5%` > 0 & `97.5%` > 0) | (`2.5%` < 0 & `97.5%` < 0), 2) %>%
  autofit() %>%
  merge_v(j=c("model", "WAIC")) %>%
  fix_border_issues() %>%
  border_inner_h()

save_as_docx(
  "Effects in informativity models with fixed and random effects" = effs_table_Main, 
  path = "output_tables/table_Main_effects_Informativity_social_models.docx")


effs_plot <- effs %>%
  #filter(WAIC <= top_9) %>%
  rename(lower=2,
         upper = 4,
         mean = 3) %>% #mean here refers to 0.5 quantile 
  #filter(!effect == "Intercept") %>%
  mutate(effect = factor(effect, levels=c("phylogenetic SD", "spatial SD", "Intercept", "social SD:\nL1", "L1", "social SD:\nL2 proportion", "L2 proportion", "Neighbours", "Education", "Official status", "L1*L2 proportion"))) %>%
  mutate(WAIC = round(WAIC, 2)) %>%
  unite("model", model, WAIC, sep = ",\nWAIC: ", remove=FALSE) %>%
  group_by(WAIC) %>%
  arrange(WAIC) %>%
  mutate(model = forcats::fct_reorder(as.factor(model), WAIC)) %>% #reordering levels within model based on WAIC values
  mutate(model = factor(model, levels=rev(levels(model)))) #reversing the order


#plot modified from function ggregplot::Efxplot
cols = c(brewer.pal(12, "Paired"))
cols = c(cols[c(12, 10)], "gray50", cols[c(1:8)])

show_col(cols)

plot_1 <- ggplot(effs_plot,
                 aes(y = as.factor(model),
                     x = mean,
                     group = effect,
                     colour = effect)) +
  geom_pointrangeh(aes(xmin = lower, xmax = upper), position = position_dodge(w = 0.9), size = 1.5) +
  geom_vline(aes(xintercept = 0),lty = 2) + labs(x = NULL) + #coord_flip() +
  scale_color_manual(values=cols) +
  ylab("Model of informativity") + xlab("Estimate") + labs(color = "Effect") + theme_classic() +
  theme(axis.text=element_text(size=50),
        legend.text=element_text(size=50),
        axis.title=element_text(size=50),
        legend.title=element_text(size=50),
        legend.spacing.y = unit(1.5, 'cm')) +
  guides(color = guide_legend(reverse = TRUE, byrow = TRUE))



#plot_1
ggsave(filename = 'output/SP_models_plot_Informativity_social_models.jpg',
       plot_1, height = 20, width = 45)


#saving hyperparameters: Gaussian observations
for (i in 1:length(marginals_hyperpar_list_gaussian)) {
  marginals_hyperpar_list_gaussian[[i]]$model <- names(marginals_hyperpar_list_gaussian)[i]
}
marginals_hyperpar_list_gaussian <- dplyr::bind_rows(marginals_hyperpar_list_gaussian)

write.csv(marginals_hyperpar_list_gaussian, "output_tables/Informativity_social_models_marginals_hyperpar_gaussian.csv") 

#saving hyperparameters: phylogenetic
for (i in 1:length(marginals_hyperpar_list_phy)) {
  marginals_hyperpar_list_phy[[i]]$model <- names(marginals_hyperpar_list_phy)[i]
}
marginals_hyperpar_list_phy <- dplyr::bind_rows(marginals_hyperpar_list_phy)

write.csv(marginals_hyperpar_list_phy, "output_tables/Informativity_social_models_marginals_hyperpar_phylogenetic.csv")

#saving hyperparameters: spatial
for (i in 1:length(marginals_hyperpar_list_spa)) {
  marginals_hyperpar_list_spa[[i]]$model <- names(marginals_hyperpar_list_spa)[i]
}
marginals_hyperpar_list_spa <- dplyr::bind_rows(marginals_hyperpar_list_spa)

write.csv(marginals_hyperpar_list_spa, "output_tables/Informativity_social_models_marginals_hyperpar_spatial.csv")


#saving summaries of random effects: phylogenetic
for (i in 1:length(summary_random_list_phy)) {
  summary_random_list_phy[[i]]$model <- names(summary_random_list_phy)[i]
}
summary_random_list_phy <- dplyr::bind_rows(summary_random_list_phy)

write.csv(summary_random_list_phy, "output_tables/Informativity_social_models_summary_random_phy.csv")

#saving summaries of random effects: spatial
for (i in 1:length(summary_random_list_spa)) {
  summary_random_list_spa[[i]]$model <- names(summary_random_list_spa)[i]
}
summary_random_list_spa <- dplyr::bind_rows(summary_random_list_spa)

write.csv(summary_random_list_spa, "output_tables/Informativity_social_models_summary_random_spa.csv")