File size: 22,543 Bytes
649d4d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
cat(rep('=', 80),
    '\n\n',
    'OUTPUT FROM: shorts/06_analysis_multipletesting.R',
    '\n\n',
    sep = ''
    )
    
library(data.table)
library(car)
library(sandwich)
library(lmtest)
library(ggplot2)
library(tidyverse)

###############
## functions ##
###############

`%.%` <- paste0

simes <- function(ps){
  min(sort(length(ps) * ps / rank(ps)))
}

### functions to handle inconsistent interaction ordering of mlm() ###

## convert interaction terms of form 'b#:a#' to 'a#:b#'
reorder.interaction.names <- function(x, prefix = ''){
  x <- gsub('^' %.% prefix, '', x)
  sapply(strsplit(x, ':'),
         function(y){
           paste(sort(y), collapse = ':')
         })
}

## take term of form 'a1:b1', look up in vector of form 'b#:a#, return 'b1:a1'
convert.interaction.names <- function(x, y, prefix.y = ''){
  ind <- match(reorder.interaction.names(x),
               reorder.interaction.names(y, prefix = prefix.y)
  )
  return(y[ind])
}

## modified from print.linearHypothesis.mlm to use alternate df & return pvals
##   (print method is responsible for doing the actual computation of pvals)
extract.lht <- function(x,
                        SSP = TRUE,
                        SSPE = SSP,
                        digits = getOption('digits'),
                        df.residual = x$df.residual
){
  test <- x$test
  if (!is.null(x$P) && SSP) {
    P <- x$P
    cat("\n Response transformation matrix:\n")
    attr(P, "assign") <- NULL
    attr(P, "contrasts") <- NULL
    print(P, digits = digits)
  }
  if (SSP) {
    cat("\nSum of squares and products for the hypothesis:\n")
    print(x$SSPH, digits = digits)
  }
  if (SSPE) {
    cat("\nSum of squares and products for error:\n")
    print(x$SSPE, digits = digits)
  }
  if ((!is.null(x$singular)) && x$singular) {
    warning("the error SSP matrix is singular; multivariate tests are unavailable")
    return(invisible(x))
  }
  SSPE.qr <- qr(x$SSPE)
  eigs <- Re(eigen(qr.coef(SSPE.qr, x$SSPH), symmetric = FALSE)$values)
  tests <- matrix(NA, 4, 4)
  rownames(tests) <- c("Pillai", "Wilks", "Hotelling-Lawley",
                       "Roy")
  if ("Pillai" %in% test)
    tests[1, 1:4] <- car:::Pillai(eigs, x$df, df.residual)
  if ("Wilks" %in% test)
    tests[2, 1:4] <- car:::Wilks(eigs, x$df, df.residual)
  if ("Hotelling-Lawley" %in% test)
    tests[3, 1:4] <- car:::HL(eigs, x$df, df.residual)
  if ("Roy" %in% test)
    tests[4, 1:4] <- car:::Roy(eigs, x$df, df.residual)
  tests <- na.omit(tests)
  ok <- tests[, 2] >= 0 & tests[, 3] > 0 & tests[, 4] > 0
  ok <- !is.na(ok) & ok
  tests <- cbind(x$df, tests, pf(tests[ok, 2], tests[ok, 3],
                                 tests[ok, 4], lower.tail = FALSE))
  colnames(tests) <- c("Df", "test stat", "approx F", "num Df",
                       "den Df", "Pr(>F)")
  tests <- structure(as.data.frame(tests),
                     heading = paste("\nMultivariate Test",
                                     if (nrow(tests) > 1)
                                       "s", ": ", x$title, sep = ""),
                     class = c("anova",
                               "data.frame"
                     )
  )
  return(tests)
}

###############
## load data ##
###############

d <- fread('../results/intermediate data/shorts/qualtrics_w12_clean_ytrecs_may2024.csv')

##############
## controls ##
##############

platform.controls <- c('age_cat',
                       'male',
                       'pol_interest',
                       'freq_youtube')

mwpolicy.controls <- 'mw_index_pre'

media.controls <- c('trust_majornews',
                    'trust_youtube',
                    'fabricate_majornews',
                    'fabricate_youtube')

affpol.controls <- c('affpol_smart',
                     'affpol_comfort')

controls.raw <- unique(c(platform.controls,
                         mwpolicy.controls,
                         media.controls,
                         affpol.controls))

## transform control variables by creating dummies and demeaning
controls.trans <- list()
for (j in controls.raw){
  ## convert to dummies if needed
  controls.j <- model.matrix(as.formula('~ 0 + ' %.% j),
                             model.frame(as.formula('~ 0 + ' %.% j),
                                         data = d,
                                         na.action = 'na.pass'
                             )
  )
  ## demean by column
  controls.j <- sweep(controls.j,
                      MARGIN = 2,
                      STATS = colMeans(controls.j, na.rm = TRUE),
                      FUN = `-`,
  )
  colnames(controls.j) <- make.names(colnames(controls.j))
  ## remove control from original data
  d[[j]] <- NULL
  ## reinsert transformed control
  d <- cbind(d, controls.j)
  ## keep track of which original controls map to which transformed controls
  controls.trans[[j]] <- colnames(controls.j)
}

## map original control variables to transformed versions
platform.controls <- unlist(controls.trans[platform.controls])
mwpolicy.controls <- unlist(controls.trans[mwpolicy.controls])
media.controls <- unlist(controls.trans[media.controls])
affpol.controls <- unlist(controls.trans[affpol.controls])

### Platform interactions ###
d <- d %>% filter(!is.na(interface_duration)) # -- 929 observations

##############
## outcomes ##
##############

### HYPOTHESIS FAMILY: MIN WAGE POLICY ATTITUDES ###

## ONLY HAVE ONE OUTCOME
mwpolicy.outcomes <- 'mw_index'

outcomes <- unique(c(mwpolicy.outcomes))

################
## treatments ##
################

## CREATE ATTITUDE DUMMIES
# 1-LIBERALS, 2-MODERATES, 3-CONSERVATIVES
d[, attitude := c('pro', 'neutral', 'anti')[thirds]]
d[, attitude.pro := as.numeric(attitude == 'pro')]
d[, attitude.neutral := as.numeric(attitude == 'neutral')]
d[, attitude.anti := as.numeric(attitude == 'anti')]

## CREATE SEQUENCE DUMMIES -- AC, PC, AI, PI
d[, recsys.ac := as.numeric(treatment_arm %like% 'ac')]
d[, recsys.pc := as.numeric(treatment_arm %like% 'pc')]
d[, recsys.ai := as.numeric(treatment_arm %like% 'ai')]
d[, recsys.pi := as.numeric(treatment_arm %like% 'pi')]

# (a)  Increasing vs.  Constant assignment among Pro participants;
# (b)  Increasing vs.  Constant assignment among Anti participants;
# (c)  Increasing  vs.   Constant  assignment  among  Moderate  participants  assigned  to  a  Prosequence;
# (d)  Increasing vs.  Constant assignment among moderate participants assigned to an Antisequence;
# (e)  Pro vs.  Anti sequence assignment among moderate participants with Increasing assignment;
# (f)  Pro vs.  Anti seed among moderate participants with Constant assignment.

# Treatments:
treatments <- c('attitude.pro:recsys.pi', # (a)
                'attitude.pro:recsys.pc', # (a)
                'attitude.anti:recsys.ai', # (b)
                'attitude.anti:recsys.ac', # (b)
                'attitude.neutral:recsys.ai', # (d-e)
                'attitude.neutral:recsys.pi', # (c-e)
                'attitude.neutral:recsys.ac', # (d-f)
                'attitude.neutral:recsys.pc') # (c-f)

# Contrasts:
contrasts <- rbind(
  # Increasing vs. Constant assignment among Pro participants
  i = c(treat = 'attitude.pro:recsys.pi',
        ctrl = 'attitude.pro:recsys.pc'
  ),
  # Increasing vs. Constant assignment among Anti participants
  ii = c(treat = 'attitude.anti:recsys.ai',
         ctrl = 'attitude.anti:recsys.ac'
  ),
  # Increasing vs. Constant assignment among Moderate participants assigned to a Pro sequence
  iii = c(treat = 'attitude.neutral:recsys.pi',
          ctrl = 'attitude.neutral:recsys.pc'
  ),
  # Increasing vs. Constant assignment among moderate participants assigned to an Anti sequence
  iv = c(treat = 'attitude.neutral:recsys.ai',
         ctrl = 'attitude.neutral:recsys.ac'
  ),
  # Pro vs. Anti sequence assignment among moderate participants with Increasing assignment
  v = c(treat = 'attitude.neutral:recsys.ai',
        ctrl = 'attitude.neutral:recsys.pi'
  ),
  # Pro vs. Anti sequence assignment among moderate participants with Constant assignment
  vi = c(treat = 'attitude.neutral:recsys.ac',
         ctrl = 'attitude.neutral:recsys.pc'
  )
)

##########################
## hierarchical testing ##
##########################

## initialize top layer p-values:
## does treatment have any effect on any outcome in family
families <- c('mwpolicy')
layer1.pvals <- rep(NA_real_, length(families))
layer1.notes <- rep('', length(families))
names(layer1.pvals) <- families

## initialize 2nd layer p-values:
##   which treatment has detectable effect?
contrast.pvals <- rep(NA_real_, nrow(contrasts))
names(contrast.pvals) <- paste(contrasts[, 'treat'],
                               contrasts[, 'ctrl'],
                               sep = '.vs.'
)
layer2.pvals <- list( mwpolicy = contrast.pvals)
rm(contrast.pvals)

## initialize 3rd layer p-values:
##   on which specific outcome in family?
layer3.pvals <- list()
layer3.ests <- list()
layer3.ses <- list()
layer3.notes <- list()
for (i in 1:length(families)){
  family <- families[i]
  layer3.pvals[[family]] <- list()
  layer3.ests[[family]] <- list()
  layer3.ses[[family]] <- list()
  layer3.notes[[family]] <- list()
  outcomes <- get(family %.% '.outcomes')
  for (j in 1:nrow(contrasts)){
    contrast <- paste(contrasts[j, 'treat'],
                      contrasts[j, 'ctrl'],
                      sep = '.vs.'
    )
    layer3.pvals[[family]][[contrast]] <- numeric(0)
    layer3.ests[[family]][[contrast]] <- numeric(0)
    layer3.ses[[family]][[contrast]] <- numeric(0)
    for (k in 1:length(outcomes)){
      outcome <- outcomes[k]
      layer3.pvals[[family]][[contrast]][outcome] <- NA_real_
      layer3.ests[[family]][[contrast]][outcome] <- NA_real_
      layer3.ses[[family]][[contrast]][outcome] <- NA_real_
      layer3.notes[[family]][outcome] <- ''
    }
  }
}

### begin nested analyses ###
for (i in 1:length(families)){
  
  family <- families[i]
  family.outcomes <- get(family %.% '.outcomes')
  family.controls <- get(family %.% '.controls')

  
  family.controls.interactions <- as.character(
    outer(treatments,
          family.controls,
          FUN = function(x, y) x %.% ':' %.% y
    )
  )
  
  family.formula <-
    'cbind(' %.%                # outcomes
    paste(family.outcomes,
          collapse = ', '
    ) %.%  ') ~\n0 +\n' %.%
    paste(treatments,           # treatments (base terms)
          collapse = ' +\n'
    ) %.% ' +\n' %.%
    paste(family.controls,      # controls (base terms)
          collapse = ' +\n'
    )##  %.% ' +\n' %.%
  ## paste(                      # treat-ctrl interactions
  ##   family.controls.interactions,
  ##   collapse = ' +\n'
  ## )
  
  cat(rep('=', 80),
      '\n\nHYPOTHESIS FAMILY: ',
      family,
      '\n\nrunning mlm:\n\n',
      family.formula,
      '\n\n',
      sep = ''
  )
  
  ## run model
  family.mod <- lm(family.formula, d)
  
  ## hack to eliminate NA coefs
  if (any(is.na(coef(family.mod)))){
    if ('mlm' %in% class(family.mod)){
      drop <- rownames(coef(family.mod))[is.na(coef(family.mod))[, 1]]
    } else {
      drop <- names(coef(family.mod))[is.na(coef(family.mod))]
    }
    drop <- convert.interaction.names(drop,
                                      c(family.controls,
                                        family.controls.interactions
                                      )
    )
    layer1.notes[[i]] <-
      layer1.notes[[i]] %.%
      'dropped the following coefs: ' %.%
      paste(drop, sep = ', ') %.%
      '\n\n'
    family.formula <- gsub(
      '\\s+\\+\\s+(' %.% paste(drop, collapse = '|') %.% ')',
      '',
      family.formula
    )
    family.mod <- lm(family.formula, d)
  }
  
  family.vcov <- vcovHC(family.mod)
  if (is.null(dim(coef(family.mod)))){
    coef.names <- names(coef(family.mod))
  } else {
    coef.names <- rownames(coef(family.mod))
  }
  
  ### top layer: test overall significance of all contrasts on all outcomes ###
  ## convert interaction terms to whatever mlm() named it
  treats <- convert.interaction.names(contrasts[, 'treat'], coef.names)
  ctrls <- convert.interaction.names(contrasts[, 'ctrl'], coef.names)
  
  ## test jointly
  lht.attempt <- tryCatch({
    if ('mlm' %in% class(family.mod)){
      contrast.lht <- linearHypothesis(
        family.mod,
        vcov. = family.vcov,
        hypothesis.matrix = sprintf('%s - %s', treats, ctrls),
        rhs = matrix(0, nrow = nrow(contrasts), ncol = length(family.outcomes)),
        test = 'Pillai'
      )
      layer1.pvals[[i]] <- extract.lht(contrast.lht)[, 'Pr(>F)']
    } else {
      contrast.lht <- linearHypothesis(
        family.mod,
        vcov. = family.vcov,
        hypothesis.matrix = sprintf('%s - %s', treats, ctrls),
        rhs = matrix(0, nrow = nrow(contrasts), ncol = length(family.outcomes)),
        test = 'F'
      )
      layer1.pvals[[i]] <- contrast.lht[['Pr(>F)']][2]
    }
  },
  error = function(e){
    warning(sprintf('caught error in %s family:', family), e)
    ## return error as string for inclusion in notes
    'caught error: ' %.%
      e %.%
      '\n\n'
  })
  if (lht.attempt %like% 'caught error'){
    layer1.notes[[i]] <-
      layer1.notes[[i]] %.% lht.attempt
  }

  ### layer 2: test each contrast individually on all outcomes ###
  
  for (j in 1:nrow(contrasts)){
    ## test group equality on all outcomes
    if ('mlm' %in% class(family.mod)){
      contrast.lht <-
        linearHypothesis(
          family.mod,
          vcov. = family.vcov,
          hypothesis.matrix = sprintf('%s - %s', treats[j], ctrls[j]),
          rhs = matrix(0, nrow = 1, ncol = length(family.outcomes)),
          test = 'Pillai'
        )
      layer2.pvals[[i]][j] <- extract.lht(contrast.lht)[, 'Pr(>F)']
    } else {
      contrast.lht <- linearHypothesis(
        family.mod,
        vcov. = family.vcov,
        hypothesis.matrix = sprintf('%s - %s', treats[j], ctrls[j]),
        rhs = matrix(0, nrow = 1, ncol = length(family.outcomes)),
        test = 'F'
      )
      layer2.pvals[[i]][j] <- contrast.lht[['Pr(>F)']][2]
    }
  }
  
  ### layer 3: test each contrast on each outcome individually ###
  
  for (k in 1:length(family.outcomes)){
    
    outcome <- family.outcomes[k]
    
    outcome.formula <-
      outcome %.% ' ~\n0 +\n' %.%
      paste(treatments,         # treatments (base terms)
            collapse = ' +\n'
      ) %.% ' +\n' %.%
      paste(family.controls,      # controls (base terms)
            collapse = ' +\n'
      )##  %.% ' +\n' %.%
    ## paste(                      # treat-ctrl interactions
    ##   family.controls.interactions,
    ##   collapse = ' +\n'
    ## )
    
    cat(rep('-', 40), '\n\nrunning lm:\n\n', outcome.formula, '\n\n', sep = '')
    
    outcome.mod <- lm(outcome.formula, d)
    ## hack to eliminate NA coefs
    if (any(is.na(coef(outcome.mod)))){
      drop <- names(coef(outcome.mod))[is.na(coef(outcome.mod))]
      drop <- convert.interaction.names(drop,
                                        c(family.controls,
                                          family.controls.interactions
                                        )
      )
      layer3.notes[[i]][k] <-
        layer3.notes[[i]][k] %.%
        'dropped the following coefs: ' %.%
        paste(drop, sep = ', ') %.%
        '\n\n'
      outcome.formula <- gsub(
        '\\s+\\+\\s+(' %.% paste(drop, collapse = '|') %.% ')',
        '',
        outcome.formula
      )
      outcome.mod <- lm(outcome.formula, d)
    }
    
    outcome.vcov <- vcovHC(outcome.mod)
    if (any(!is.finite(outcome.vcov))){
      outcome.vcov <- vcov(outcome.mod)
      layer3.notes[[i]][k] <-
        layer3.notes[[i]][k] %.%
        'falling back to non-robust vcov\n\n'
    }
    coef.names <- names(coef(outcome.mod))
    
    for (j in 1:nrow(contrasts)){
      
      ## convert this interaction term to whatever llm() named it
      treat <- convert.interaction.names(contrasts[j, 'treat'], coef.names)
      ctrl <- convert.interaction.names(contrasts[j, 'ctrl'], coef.names)
      ## test group equality on this outcome
  
      
      contrast.lht <- linearHypothesis(
        outcome.mod,
        vcov. = outcome.vcov,
        hypothesis.matrix = sprintf('%s - %s', treat, ctrl),
        test = 'F'
      )
      
      layer3.pvals[[i]][[j]][k] <- contrast.lht[['Pr(>F)']][2]
      layer3.ests[[i]][[j]][k] <- (
        coef(outcome.mod)[treat] - coef(outcome.mod)[ctrl]
      ) ## * attr(d[[outcome]], 'scaled:scale')  # note: uncomment if rescaling
      layer3.ses[[i]][[j]][k] <- sqrt(
        outcome.vcov[treat, treat] +
          outcome.vcov[ctrl, ctrl] -
          2 * outcome.vcov[treat, ctrl]
      )
    }
  }
}

#################################
## multiple testing correction ##
#################################

thresh <- .05

## if layer-1 f-test is infeasible for a family due to collinearity,
##   obtain layer-1 p-values for that family by simes
for (i in which(is.na(layer1.pvals))){
  layer1.pvals[i] <- simes(layer2.pvals[[i]])
}

## multiple testing adjustment for layer 1
layer1.pvals.adj <- p.adjust(layer1.pvals, 'BH')
layer1.nonnull.prop <- mean(layer1.pvals.adj < thresh)

## test layer-2 hypotheses only if layer 1 passes
layer2.pvals.adj <- layer2.pvals  # start by copying unadjusted layer-2 p-values
layer2.nonnull.prop <- rep(NA, length(layer1.pvals.adj))
names(layer2.nonnull.prop) <- names(layer1.pvals.adj)
for (i in 1:length(layer1.pvals)){
  if (layer1.pvals.adj[i] < thresh){  # if layer 1 passes
    ## adjust for multiplicity within layer 2...
    layer2.pvals.adj[[i]] <- p.adjust(layer2.pvals[[i]], 'BH')
    ## ... and inflate to account for selection at layer 1
    layer2.pvals.adj[[i]] <-
      pmin(layer2.pvals.adj[[i]] / layer1.nonnull.prop, 1)
    ## keep track of selection at layer 2 for use in layer 3
    layer2.nonnull.prop[i] <- mean(layer2.pvals.adj[[i]] < thresh)
  } else {  # if layer 1 fails
    layer2.pvals.adj[[i]] <- rep(NA_real_, length(layer2.pvals[[i]]))
    names(layer2.pvals.adj[[i]]) <- names(layer2.pvals[[i]])
  }
}

## test layer-3 hypotheses only if layers 1 & 2 pass
layer3.pvals.adj <- layer3.pvals  # start by copying unadjusted layer-3 p-values
for (i in 1:length(layer1.pvals.adj)){
  for (j in 1:length(layer2.pvals.adj[[i]])){
    ##
    if (layer1.pvals.adj[i] < thresh &&      # if layer 1 passes...
        layer2.pvals.adj[[i]][j] < thresh  # ... and if layer 2 passes
    ){
      ## adjust for multiplicity within layer 3...
      layer3.pvals.adj[[i]][[j]] <- p.adjust(layer3.pvals[[i]][[j]], 'BH')
      ## ... and inflate to account for selection at layer 1
      layer3.pvals.adj[[i]][[j]] <- pmin(
        layer3.pvals.adj[[i]][[j]] / layer1.nonnull.prop / layer2.nonnull.prop[i],
        1
      )
    } else {
      layer3.pvals.adj[[i]][[j]] <- rep(NA_real_, length(layer3.pvals[[i]][[j]]))
      names(layer3.pvals.adj[[i]][[j]]) <- names(layer3.pvals[[i]][[j]])
    }
  }
}

pvals.adj <- data.table(layer1 = character(0),
                        layer2 = character(0),
                        layer3 = character(0),
                        p.adj = numeric(0),
                        est = numeric(0),
                        se = numeric(0)
)
for (i in 1:length(layer1.pvals.adj)){
  pvals.adj <- rbind(pvals.adj,
                     data.table(layer1 = names(layer1.pvals.adj)[i],
                                layer2 = 'overall',
                                layer3 = 'overall',
                                p.adj = layer1.pvals.adj[i],
                                est = NA_real_,
                                se = NA_real_
                     )
  )
  for (j in 1:length(layer2.pvals.adj[[i]])){
    pvals.adj <- rbind(pvals.adj,
                       data.table(layer1 = names(layer1.pvals.adj)[i],
                                  layer2 = names(layer2.pvals.adj[[i]])[j],
                                  layer3 = 'overall',
                                  p.adj = layer2.pvals.adj[[i]][j],
                                  est = NA_real_,
                                  se = NA_real_
                       )
    )
    for (k in 1:length(layer3.pvals.adj[[i]][[j]])){
      pvals.adj <- rbind(pvals.adj,
                         data.table(layer1 = names(layer1.pvals.adj)[i],
                                    layer2 = names(layer2.pvals.adj[[i]])[j],
                                    layer3 = names(layer3.pvals.adj[[i]][[j]])[k],
                                    p.adj = layer3.pvals.adj[[i]][[j]][k],
                                    est = layer3.ests[[i]][[j]][k],
                                    se = layer3.ses[[i]][[j]][k]
                         )
      )
    }
  }
}

## write out
fwrite(pvals.adj, '../results/padj_basecontrol_may2024.csv')


## prettify for reading
pvals.adj.pretty <- pvals.adj
colnames(pvals.adj.pretty) <- gsub('layer1',
                                   'layer1_hypothesisfamily',
                                   colnames(pvals.adj.pretty)
)
colnames(pvals.adj.pretty) <- gsub('layer2',
                                   'layer2_treatmentcontrast',
                                   colnames(pvals.adj.pretty)
)
colnames(pvals.adj.pretty) <- gsub('layer3',
                                   'layer3_specificoutcome',
                                   colnames(pvals.adj.pretty)
)

pvals.adj.pretty[, layer2_treatmentcontrast := gsub(
  'attitude\\.(pro|anti|neutral)(:assg\\.(inc|cons))?:recsys.(ca|cp|ip|ia)',
  '\\1 \\3 \\4',
  layer2_treatmentcontrast
)]
pvals.adj.pretty[, layer2_treatmentcontrast := gsub(
  '.vs.',
  ' - ',
  layer2_treatmentcontrast,
  fixed = TRUE
)]
pvals.adj.pretty[, layer2_treatmentcontrast := gsub(
  ' +',
  ' ',
  layer2_treatmentcontrast
)]
fwrite(pvals.adj.pretty,
       '../results/padj_basecontrol_pretty_ytrecs_may2024.csv'
)

# pvals.adj.pretty[p.adj < .05 & layer3_specificoutcome != 'overall',]

################################
######### OMNIBUS TEST #########
################################

# Step 1: Create a binary variable indicating increasing condition
d$is_increasing <- ifelse(d$treatment_arm == "pi" | d$treatment_arm == "ai", 1, 0)

# Step 2: Reverse values for individuals in the Pro condition
d$mw_index_pre[d$treatment_arm %like% "pi|pc"] <- 1 - d$mw_index_pre[d$treatment_arm %like% "pi|pc"]
d$mw_index[d$treatment_arm %like% "pi|pc"] <- 1 - d$mw_index[d$treatment_arm %like% "pi|pc"]

# Step 3: Perform the linear regression (omnibus test)
model <- lm(I(mw_index - mw_index_pre) ~ is_increasing, data = d)

# View the summary of the model
summary(model)
rm(list = ls())