Repository navigation
Expand file tree
/
Copy path07-coding2x2.Rmd
More file actions
executable file
·587 lines (444 loc) · 46.8 KB
/
Copy path07-coding2x2.Rmd
File metadata and controls
executable file
·587 lines (444 loc) · 46.8 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
# Contrast coding for designs with two predictor variables {#ch:coding2x2}
```{r}
library(knitr)
library(kableExtra)
library(tidyverse)
library(brms)
library(bcogsci)
library(papaja)
library(MASS)
library(hypr)
library(bcogsci)
```
Chapter\ \@ref(ch:contr) provides a basic introduction into contrast coding in situations where there is one predictor variable, i.e., one factor, which can be tested using one specified contrast matrix. Here, we will investigate how contrast coding generalizes to situations where there is more than one predictor variables. This could either be a situation where two factors are present or where one factor is paired with a continuous predictor variables, i.e., a covariate. We first discuss contrast coding for the case of two factors (for $2 \times 2$ designs; see section\ \@ref(sec:MR:ANOVA)) and then go on to investigate situations where one predictor is a factor and the other predictor is a continuous covariate (see section\ \@ref(sec:contrast:covariate)). Moreover, one problem in the analysis of interactions occurs in situations where the model is not linear, but has some non-linear link function, such as e.g., in logistic models or when assuming a log-normally distributed dependent variable. In these situations, the model makes predictions for each condition (i.e., design cell) at the latent level of the linear model. However, sometimes it is important to translate these model predictions to the level of the observations (e.g., to probabilities in a logistic regression model). We will discuss how this can be implemented in section\ \@ref(sec:interactions:NLM). Now, we first start by treating contrast coding in a factorial 2 x 2 design.
## Contrast coding in a factorial 2 x 2 design {#sec:MR:ANOVA}
In chapter\ \@ref(ch:contr) in section\ \@ref(sec:4levelFactor), we have used a data set with one 4-level factor. Here, we assume that the exact same four means come from an $A(2) \times B(2)$ between-subject-factor design rather than an F(4) between-subject-factor design. We load the artificial, simulated data and show summary statistics in Table\ \@ref(tab:cTab4Means) and in Figure \@ref(fig:twobytwosimdatFig). The means and standard deviations are exactly the same as in Figure \@ref(fig:helmertsimdatFig) and in Table\ \@ref(tab:cTab3Means).
```{r, echo=FALSE, message=FALSE}
data("df_contrasts4")
table4 <- df_contrasts4 %>% group_by(A, B) %>% # plot interaction
dplyr::summarise(N = length(DV), M = mean(DV), SD = sd(DV), SE = SD / sqrt(N))
GM <- mean(table4$M) # Grand Mean
table4a <- as.data.frame(table4)
names(table4a) <- c(
"Factor A", "Factor B", "N data",
"Means", "Std. dev.", "Std. errors"
)
```
```{r twobytwosimdatFig, fig=TRUE, include=TRUE, echo=FALSE, cache=FALSE, fig.width=5, fig.height=3, fig.cap = "Means and error bars (showing standard errors) for a simulated data-set with a two-by-two between-subjects factorial design."}
(plot2 <- qplot(x = A, y = M, group = B, linetype = B, shape = B, data = table4, geom = c("point", "line")) +
labs(y = "Dependent variable", x = "Factor A", colour = "Factor B", linetype = "Factor B", shape = "Factor B") +
geom_errorbar(aes(max = M + SE, min = M - SE), width = 0))
```
```{r cTab4Means, echo=FALSE, results = "asis"}
# apa_table(table4a, placement="b", digits=1,
# caption="Summary statistics per condition for the simulated data.")
kbl(table4a,
digits = 1, booktabs = T, position = "h", vline = "", # format="latex",
caption = "Summary statistics per condition for the simulated data."
)
```
### The difference between an ANOVA and a multiple regression
Let's compare the traditional ANOVA with multiple regression for analyzing these data.
```{r, echo=TRUE, message=FALSE, warning=FALSE}
# ANOVA: B_A(2) times B_B(2)
fit_AB_aov <- afex::aov_car(DV ~ A * B + Error(id), data = df_contrasts4)
# MR: B_A(2) times B_B(2)
fit_AB_mr <- lm(DV ~ 1 + A * B, data = df_contrasts4)
```
```{r table16, eval=FALSE, echo=FALSE, results="asis"}
tab16 <- round(data.frame(summary(fit_AB_aov)), 3)
names(tab16) <- c("DF(num)", "DF(den)", "MSE", "F", "ges", "p")
tab16 <- cbind(Effect = row.names(tab16), tab16)
row.names(tab16) <- NULL
# apa_table(tab16, placement="!htbp", caption="Estimated ANOVA model.")
# papaja::apa_table(papaja::apa_print(fit_AB_aov)$table, placement="!htbp",
# caption="Estimated ANOVA model.")
kbl(tab16, booktabs = T, position = "h", vline = "", caption = "Estimated ANOVA model.") # format="latex",
```
```{r table17, echo=FALSE, results="asis", eval = TRUE}
tab17 <- data.frame(round(coef(summary(fit_AB_mr)), 3))
names(tab17) <- c("Estimate", "Std. Error", "t", "p")
tab17 <- cbind(Predictor = row.names(tab17), tab17)
row.names(tab17) <- NULL
# apa_table(tab17, placement="!htbp", caption="Estimated regression model.")
# papaja::apa_table(papaja::apa_print(fit_AB_mr, digits=0, est_name="Estimate")$table, placement="!htbp",
# caption="Estimated regression model.")
kbl(tab17, booktabs = T, position = "h", vline = "", caption = "Estimated regression model.") # format="latex",
```
The results from the two analyses, shown in the R output and in Table \@ref(tab:table17), are very different.
How do we see these are different? Notice that it is possible to compute F-values from t-values from the fact that $F(1,df) = t(df)^2$ [@snedecor1967statistical] (where $df$ indicates degrees of freedom). When applying this to the above multiple regression model, the F-value for factor $A$ (i.e., $AA2$) is $0.00^2 = 0$. This is obviously not the same as in the ANOVA, where the F-value for factor $A$ is $5$. Likewise, in the multiple regression factor $B$ (i.e., $BB2$) has an F-value of $1.58^2 = 2.5$, which also does not correspond to the F-value for factor $B$ in the ANOVA of $20$. Interestingly, however, the F-value for the interaction is identical in both models, as $2.24^2 = 5$.
The reason that the results from the ANOVA and the results from the multiple regression are different is that one needs sum contrasts in the linear model to get the conventional tests from an ANOVA model. (This is true for factors with two levels, but does not generalize to factors with more levels.)
```{r, echo=TRUE, message=FALSE, warning=FALSE, error=FALSE}
# define sum contrasts:
contrasts(df_contrasts4$A) <- contr.sum(2)
contrasts(df_contrasts4$B) <- contr.sum(2)
# frequentist LM
fit_AB_mr.sum <- lm(DV ~ 1 + A * B, data = df_contrasts4)
```
```{r table18, echo=FALSE, results="asis"}
tab18 <- data.frame(round(coef(summary(fit_AB_mr.sum)), 3))
names(tab18) <- c("Estimate", "Std. Error", "t", "p")
tab18 <- cbind(Predictor = row.names(tab18), tab18)
row.names(tab18) <- NULL
kbl(tab18, booktabs = T, position = "h", vline = "", caption = "Regression analysis with sum contrasts.") # format="latex",
```
When using sum contrasts, the results from the multiple regression models (see Table \@ref(tab:table18)) are identical to the results from the ANOVA (see R output<!--Table \@ref(tab:table16)-->). Factor $A$ now has $t^2=-2.24^2 = 5$, factor $B$ has $t^2=-4.47^2 = 20$, and the interaction has $t^22.24^2 = 5$. All F-values are now the same as in the ANOVA model.
Next, we reproduce the $A(2) \times B(2)$ - ANOVA with contrasts specified for the corresponding one-way $F(4)$ ANOVA, that is by treating the $2 \times 2 = 4$ condition means as four levels of a single factor F. In other words, we go back to the data frame simulated for the analysis of repeated contrasts (see chapter\ \@ref(ch:contr), section\ \@ref(sec:4levelFactor)). We first define weights for condition means according to our hypotheses, invert this matrix, and use it as the contrast matrix for factor F in an LM. We define weights of $1/4$ and $-1/4$. We do so because (a) we want to compare the mean of two conditions to the mean of two other conditions (e.g., factor A compares $\frac{F1 + F2}{2}$ to $\frac{F3 + F4}{2}$). Moreover, (b) we want to use sum contrasts, where the regression coefficients assess half the difference between means. Together (a+b), this yields weights of $1/2 \cdot 1/2 = 1/4$. The resulting contrast matrix contains contrast coefficients of $+1$ or $-1$, showing that we successfully implemented sum contrasts. The results are identical to the previous models.
```{r, echo=FALSE}
ginv2 <- function(x) { # define a function to make the output nicer
fractions(provideDimnames(ginv(x), base = dimnames(x)[2:1]))
}
```
```{r, echo=TRUE, message=FALSE, warning=FALSE, error=FALSE}
data("df_contrasts3")
t(fractions(HcInt <- rbind(
A = c(F1 = 1 / 4, F2 = 1 / 4, F3 = -1 / 4, F4 = -1 / 4),
B = c(F1 = 1 / 4, F2 = -1 / 4, F3 = 1 / 4, F4 = -1 / 4),
AxB = c(F1 = 1 / 4, F2 = -1 / 4, F3 = -1 / 4, F4 = 1 / 4)
)))
(XcInt <- ginv2(HcInt))
contrasts(df_contrasts3$F) <- XcInt
```
```{r, echo=TRUE, message=FALSE, warning=FALSE, error=FALSE, results="hide"}
fit_F4.sum <- lm(DV ~ 1 + F,
data = df_contrasts3
)
```
```{r, echo=TRUE}
round(summary(fit_F4.sum)$coefficients)
```
This shows that it is possible to specify the contrasts not only for each factor (e.g., here in the $2 \times 2$ design) separately. One can alternatively pool all experimental conditions (or design cells) into one large factor (here factor F with $4$ levels), and specify the contrasts for the main effects and for the interactions in the resulting one large contrast matrix simultaneously.
In this approach, it can again be very useful to apply the `hypr` package to construct contrasts for a $2 \times 2$ design. The first hypothesis estimates the main effect A, i.e., it compares the average of `F1` and `F2` to the average of `F3` and `F4`. The second parameter estimates the main effect B, i.e., it compares the average of `F1` and `F3` to the average of `F2` and `F4`. Note that we code direct differences between the averages, i.e., we implement scaled sum contrasts instead of sum contrasts. This becomes clear below as the contrast matrix contains coefficients of $+1/2$ and $-1/2$ instead of $+1$ and $-1$. The interaction term estimates the difference between differences, i.e., the difference between `F1 - F2` and `F3 - F4`.
```{r, echo=TRUE, message=FALSE, warning=FALSE, error=FALSE}
hAxB <- hypr(
A = (F1 + F2) / 2 ~ (F3 + F4) / 2,
B = (F1 + F3) / 2 ~ (F2 + F4) / 2,
AxB = (F1 - F2) / 2 ~ (F3 - F4) / 2
)
hAxB
contrasts(df_contrasts3$F) <- contr.hypothesis(hAxB)
```
```{r, echo=TRUE, message=FALSE, warning=FALSE, error=FALSE, results="hide"}
fit_F4hypr <- lm(DV ~ 1 + F,
data = df_contrasts3
)
```
```{r, echo=TRUE}
round(summary(fit_F4hypr)$coefficients)
```
The results show that the estimates have half the size as compared to the sum contrasts - this is the result of the scaling that we applied. I.e., the main effects now directly estimate the difference between averages. However, both contrasts provide the exact same hypothesis tests. Thus, the hypr package can be used to code hypotheses in a 2 x 2 design.
### Nested effects {#nestedEffects}
One can specify hypotheses that do not correspond directly to main effects and interaction of the traditional ANOVA. For example, in a $2 \times 2$ experimental design, where factor $A$ codes word frequency (low/high) and factor $B$ is part of speech (noun/verb), one can test the effect of word frequency within nouns and the effect of word frequency within verbs. Formally, $A_{B1}$ versus $A_{B2}$ are nested within levels of $B$. Differently put, simple effects of factor $A$ are tested for each of the levels of factor $B$.
In this version, we test whether there is a main effect of part of speech ($B$; as in traditional ANOVA). However, instead of also estimating the second main effect word frequency, $A$, and the interaction, we estimate (1) whether the two levels of word frequency, $A$, differ for the first level of $B$ (i.e., nouns) and (2) whether the two levels of word frequency, $A$, differ for the second level of $B$ (i.e., verbs). In other words, we estimate whether there are differences for $A$ in each of the levels of $B$. Often researchers have hypotheses about these differences, and not about the interaction.
```{r, echo=TRUE, message=FALSE, warning=FALSE, error=FALSE}
t(fractions(HcNes <- rbind(
B = c(F1 = 1 / 2, F2 = -1 / 2, F3 = 1 / 2, F4 = -1 / 2),
B1xA = c(F1 = -1, F2 = 0, F3 = 1, F4 = 0),
B2xA = c(F1 = 0, F2 = -1, F3 = 0, F4 = 1)
)))
(XcNes <- ginv2(HcNes))
contrasts(df_contrasts3$F) <- XcNes
```
```{r, echo=TRUE, message=FALSE, warning=FALSE, error=FALSE, results="hide"}
fit_Nest <- lm(DV ~ 1 + F,
data = df_contrasts3
)
```
```{r, echo=TRUE}
round(summary(fit_Nest)$coefficients)
```
Regression coefficients estimate the GM, the difference for the main effect of word frequency ($A$) and the two differences (for $B$; i.e., simple main effects) within levels of word frequency ($A$).
These custom nested contrasts' columns are scaled versions of the corresponding hypothesis matrix. This is the case because the columns are orthogonal. It illustrates the advantage of orthogonal contrasts for the interpretation of regression coefficients: the underlying hypotheses being tested are already clear from the contrast matrix.
There is also a built-in R formula specification of nested designs. The order of factors in the formula from left to right specifies a top-down order of nesting within levels, i.e., here factor $A$ (word frequency) is nested within levels of the factor $B$ (part of speech). This yields the exact same result as our previous result based on custom nested contrasts:
```{r, echo=TRUE, message=FALSE, warning=FALSE, error=FALSE, results="hide"}
contrasts(df_contrasts4$A) <- c(-0.5, +0.5)
contrasts(df_contrasts4$B) <- c(+0.5, -0.5)
fit_Nest2 <- lm(DV ~ 1 + B / A,
data = df_contrasts4
)
```
```{r, echo=TRUE}
round(summary(fit_Nest2)$coefficients)
```
xxx
Note that in cases such as these, where $A_{B1}$ vs. $A_{B2}$ are nested within levels of $B$, it is necessary to include the effect of $B$ (part of speech) in the model, even if one is only interested in the effect of $A$ (word frequency) within levels of $B$ (part of speech). Leaving out factor $B$ in this case can lead to biases in parameter estimation in the case the data are not fully balanced.
Again, we show how nested contrasts can be easily implemented using `hypr`:
```{r, echo=TRUE, message=FALSE, warning=FALSE, error=FALSE}
hNest <- hypr(
B = (F1 + F3) / 2 ~ (F2 + F4) / 2,
B1xA = F3 ~ F1,
B2xA = F4 ~ F2
)
hNest
contrasts(df_contrasts3$F) <- contr.hypothesis(hNest)
```
```{r, echo=TRUE, message=FALSE, warning=FALSE, error=FALSE, results="hide"}
fit_NestHypr <- lm(DV ~ 1 + F,
data = df_contrasts3
)
```
```{r, echo=TRUE}
round(summary(fit_NestHypr)$coefficients)
```
Of course, we can also ask the reverse question: Are there differences for part of speech ($B$) in the levels of word frequency ($A$; in addition to estimating the main effect of word frequency, $A$)? That is, do nouns differ from verbs for low-frequency words ($B_{A1}$) and do nouns differ from verbs for high-frequency words ($B_{A2}$)?
```{r, echo=TRUE, message=FALSE, warning=FALSE, error=FALSE}
hNest2 <- hypr(
A = (F1 + F2) / 2 ~ (F3 + F4) / 2,
A1xB = F2 ~ F1,
A2xB = F4 ~ F3
)
hNest2
contrasts(df_contrasts3$F) <- contr.hypothesis(hNest2)
```
```{r, echo=TRUE, message=FALSE, warning=FALSE, error=FALSE, results="hide"}
fit_Nest2Hypr <- lm(DV ~ 1 + F,
data = df_contrasts3
)
```
```{r, echo=TRUE}
round(summary(fit_Nest2Hypr)$coefficients)
```
xxx
Regression coefficients estimate the GM, the difference for the main effect of word frequency ($A$) and the two part of speech effects (for $B$; i.e., simple main effects) within levels of word frequency ($A$).
### Interactions between contrasts
We have discussed above that in a $2 \times 2$ experimental design, the results from sum contrasts are equivalent to typical ANOVA results. In addition, we had also run the analysis with treatment contrasts. It was clear that the results for treatment contrasts (see Table\ \@ref(tab:table17)) did not correspond to the results from the ANOVA. However, if the results for treatment contrasts do not correspond to the typical ANOVA results, what do they then test? That is, is it still possible to meaningfully interpret the results from the treatment contrasts in a simple $2 \times 2$ design?
This leads us to a very important principle in interpreting results from contrasts: When interactions between contrasts are included in a model, then the results of one contrast actually depend on the specification of the other contrast(s) in the analysis! This may be counter-intuitive at first. However, it is very important and essential to keep in mind when interpreting results from contrasts. How does this work in detail?
The general rule to remember is that the main effect of one contrast measures its effect at the location $0$ of the other contrast(s) in the analysis. What does that mean? Let us consider the example that we use two treatment contrasts in a $2 \times 2$ design (see results in Table\ \@ref(tab:table17)). Let's take a look at the main effect of factor A. How can we interpret what this measures or tests? This main effect actually tests the effect of factor A at the "location" where factor B is coded as $0$. Factor B is coded as a treatment contrast, that is, it codes a zero at its baseline condition, which is B1. Thus, the main effect of factor A tests the effect of A nested within the baseline condition of B. We take a look at the data presented in Figure\ \@ref(fig:twobytwosimdatFig), what this nested effect should be. Figure\ \@ref(fig:twobytwosimdatFig) shows that the effect of factor A nested in B1 is $0$. If we now compare this to the results from the linear model, it is indeed clear that the main effect of factor A (see Table\ \@ref(tab:table17)) is exactly estimated as $0$. As expected, when factor B is coded as a treatment contrast, the main effect of factor A estimates the effect of A nested within the baseline level of factor B.
Next, consider the main effect of factor B. According to the same logic, this main effect estimates the effect of factor B at the "location" where factor A is $0$. Factor A is also coded as a treatment contrast, that is, it codes its baseline condition A1 as $0$. The main effect of factor B estimates the effect of B nested within the baseline condition of A. Figure\ \@ref(fig:twobytwosimdatFig) shows that this effect should be $10$; this indeed corresponds to the main effect of B as estimated in the regression model for treatment contrasts (see Table \@ref(tab:table17), the *Estimate* for BB2). As we had seen before, the interaction term, however, does not differ between the treatment contrast and ANOVA ($t^2 = 2.24^2 = F = 5.00$).
How do we know what the "location" is, where a contrast applies? For the treatment contrasts discussed here, it is possible to reason this through because all contrasts are coded as $0$ or $1$. However, how is it possible to derive the "location" in general? What we can do is to look at the hypotheses tested by the treatment contrasts (or the comparisons that are estimated) in the presence of an interaction between them by using the generalized matrix inverse. We go back to the default treatment contrasts. Then we extract the contrast matrix from the design matrix:
```{r, echo=TRUE, message=FALSE}
contrasts(df_contrasts4$A) <- contr.treatment(2)
contrasts(df_contrasts4$B) <- contr.treatment(2)
XcTr <- df_contrasts4 %>%
group_by(A, B) %>%
dplyr::summarise() %>%
model.matrix(~ 1 + A * B, .) %>%
as.data.frame() %>%
as.matrix()
rownames(XcTr) <- c("A1_B1", "A1_B2", "A2_B1", "A2_B2")
XcTr
```
This shows the treatment contrast for factors `A` and `B`, and their interaction. We can now assign this contrast matrix to a `hypr` object. `hypr` automatically converts the contrast matrix into a hypothesis matrix, such that we can read from the hypothesis matrix which comparison are being estimated by the different contrasts.
```{r, echo=TRUE}
htr <- hypr() # initialize empty hypr object
cmat(htr) <- XcTr # assign contrast matrix to hypr object
htr # look at the resulting hypothesis matrix
```
Note that the same result is obtained by applying the generalized inverse to the contrast matrix (this is what hypr does as well). An important fact is that when we apply the generalized inverse to the contrast matrix, we obtain the corresponding hypothesis matrix [for details see @schad2020capitalize].
```{r, echo=TRUE}
t(ginv2(XcTr))
```
As discussed above, the main effect of factor `A` estimates its effect nested within the baseline level of factor `B`. Likewise, the main effect of factor `B` estimates its effect nested within the baseline level of factor `A`.
How does this work for sum contrasts? They do not have a baseline condition that is coded as $0$. In sum contrasts, however, the average of the contrast coefficients is $0$. Therefore, main effects estimate the average effect across factor levels. This is what is typically also tested in standard ANOVA. Let's look at the example shown in Table\ \@ref(tab:table18): given that factor B has a sum contrast, the main effect of factor A is tested as the average across levels of factor B. Figure\ \@ref(fig:twobytwosimdatFig) shows that the effect of factor A in level B1 is $10 - 10 = 0$, and in level B2 it is $20 - 40 = -20$. The average effect across both levels is $(0 - 20)/2 = -10$. Due to the sum contrast coding, we have to divide this by 2, yielding an expected effect of $-10 / 2 = -5$. This is exactly what the main effect of factor A measures (see Table\ \@ref(tab:table18), *Estimate* for A1).
Similarly, factor B tests its effect at the location $0$ of factor A. Again, $0$ is exactly the mean of the contrast coefficients from factor A, which is coded as a sum contrast. Therefore, factor B tests the effect of B averaged across factor levels of A. For factor level A1, factor B has an effect of $10 - 20 = -10$. For factor level A2, factor B has an effect of $10 - 40 = -30$. The average effect is $(-10 - 30)/2 = -20$, which again needs to be divided by $2$ due to the sum contrast. This yields exactly the estimate of $-10$ that is also reported in Table\ \@ref(tab:table18) (*Estimate* for B1).
Again, we look at the hypothesis matrix for the main effects and the interaction:
```{r, echo=TRUE, message=FALSE}
contrasts(df_contrasts4$A) <- contr.sum(2)
contrasts(df_contrasts4$B) <- contr.sum(2)
XcSum <- df_contrasts4 %>%
group_by(A, B) %>%
dplyr::summarise() %>%
model.matrix(~ 1 + A * B, .) %>%
as.data.frame() %>%
as.matrix()
rownames(XcSum) <- c("A1_B1", "A1_B2", "A2_B1", "A2_B2")
hsum <- hypr() # initialize empty hypr object
cmat(hsum) <- XcSum # assign contrast matrix to hypr object
hsum # look at the resulting hypothesis matrix
```
This shows that each of the main effects now does not compute nested comparisons any more, but that they rather test their effect averaged across conditions of the other factor. The averaging involves using weights of $1/2$. Moreover, the regression coefficients in the sum contrast measure half the distance between conditions, leading to weights of $1/2 \cdot 1/2 = 1/4$.
The general rule to remember from these examples is that when interactions between contrasts are estimated, what a main effect of a factor estimates depends on the contrast coding of the other factors in the design! The main effect of a factor estimates the effect nested within the location zero of the other contrast(s) in an analysis. If another contrast is centered, and zero is the average of this other contrast's coefficients, then the contrast of interest tests the average effect, averaged across the levels of the other factor. Importantly, this property holds only when the interaction between two contrasts is included into a model. If the interaction is omitted and only main effects are estimated, then there is no such "action at a distance".
This may be a very surprising result for interactions of contrasts. However, it is also essential to interpreting contrast coefficients involved in interactions. It is particularly relevant for the analysis of the default treatment contrast, where the main effects estimate nested effects rather than average effects.
## One factor and one covariate {#sec:contrast:covariate}
### Estimating a group-difference and controlling for a covariate
In this section we treat the case where there are again two predictor variables for one dependent variable, but where one predictor variable is a discrete factor, and the other is a continuous covariate. Let's assume we have measured some response time (RT), e.g. in a lexical decision task. We want to predict the response time based on each subject's IQ, and we expect that higher IQ leads to shorter response times. Moreover, we have two groups of each 30 subjects. These are coded as factor F, with factor levels F1 and F2. We assume that these two groups have obtained different training programs to optimize their response times on the task. Group F1 obtained a control training, whereas group F2 obtained a training to improve lexical decisions. We want to test whether the training for better lexical decisions in group F2 actually leads to shorter response times compared to the control group F1. This is our main question of interest here, i.e., whether the training program in F2 leads to faster response times compared to the control group F1. We load the data, which is an artificially simulated data set.
```{r, echo=TRUE}
data("df_contrasts5")
str(df_contrasts5)
```
Our main effect of interest is the factor F. We want to test its effect on response times and code it using scaled sum contrasts, such that negative parameter estimates would yield support for our hypothesis that response times are faster in the training group F2:
```{r, echo=TRUE}
(contrasts(df_contrasts5$F) <- c(-0.5, +0.5))
```
We run a linear model to estimate the effect of factor F, i.e., how strongly the response times in the two groups differ from each other.
```{r, echo=TRUE, message=FALSE, warning=FALSE, error=FALSE, results="hide"}
fit_RT_F <- lm(RT ~ 1 + F,
data = df_contrasts5
)
```
```{r, echo=TRUE}
round(summary(fit_RT_F)$coefficients)
```
```{r, echo=FALSE, message=FALSE, warning=FALSE, results="hide"}
tab5 <- df_contrasts5 %>%
group_by(F) %>%
dplyr::summarize(M = mean(RT), SE = sd(RT) / sqrt(n()))
```
```{r figRTF, fig=TRUE, include=TRUE, echo=FALSE, cache=FALSE, fig.width=2.5, fig.height=3, fig.cap = "Means and error bars (showing standard errors) for a simulated data-set of response times for two different groups of subjects, who have obtained a training in lexical decisions (F2) versus have obtained a control training (F1)."}
(plot_RT <- ggplot(data = tab5, aes(x = F, y = M, ymin = M - SE, ymax = M + SE)) +
geom_bar(stat = "identity") +
geom_errorbar(width = 0.2) +
labs(y = "Response times [ms]", x = "Group (F)"))
```
We find (see model estimates and data shown in Fig.\ \@ref(fig:figRTF)) that response times in group F2 are roughly 25 ms faster than in group F1 (Estimate of $-24$). The 95\% confidence intervals do not overlap with zero. This suggests that as expected, the training program that group F2 obtained seems to be successful in speeding up response times. We could now run a Bayes factor analysis on this data set to directly test this hypothesis, and maybe this would provide evidence for a difference in response times between groups.
However, let's assume we have allocated subjects to the two groups randomly. Let's say that we also measured the IQ of each person using an IQ test. We did so, because we expected that IQ could have a strong influence on response times, and we wanted to control for this influence. We now can check whether the two groups had the same average IQ.
```{r, echo=TRUE, message=FALSE, warning=FALSE}
df_contrasts5 %>%
group_by(F) %>%
dplyr::summarize(M.IQ = mean(IQ))
```
Interestingly, group F2 did not only obtain an additional training and had faster response times, but group F2 also had a higher IQ (mean of 115) on average than group F1 (mean IQ = 85). Thus, the random allocation of subjects to the two groups seems to have created - by chance - a difference in IQs. Now we can ask the question: why may response times in group F2 be faster than in group F1? Is this because of the training program in F2? Or is this simply because the average IQ in group F2 was higher than in group F1? To investigate this question, we add both predictor variables simultaneously in a linear model. Before we enter the continuous IQ variable, we center it, by subtracting its mean. Centering covariates is generally good practice. Moreover, it is often important to z-transform the covariate, i.e., to not only subtract the mean, but also to divide by its standard deviation (this can be done as follows: `df_contrasts5$IQ.s <- scale(df_contrasts5$IQ)`). The reason why this is often important is that the estimation doesn’t work well if predictors have different scales. For the simple models we use here, the estimation works fine without z-transformation. However, for more realistic more complex models, z-transformation of covariates is often very important.
```{r, echo=TRUE, message=FALSE, warning=FALSE, error=FALSE, results="hide"}
df_contrasts5$IQ.c <- df_contrasts5$IQ - mean(df_contrasts5$IQ)
fit_RT_F_IQ <- lm(RT ~ 1 + F + IQ.c,
data = df_contrasts5
)
```
```{r, echo=TRUE}
round(summary(fit_RT_F_IQ)$coefficients, 2)
```
The results from the brms model now show that the difference in response times between groups (i.e., factor F) is not estimated to be $-25$ ms any more, but instead, the estimate is about $+7$ ms, and the 95\% confidence intervals strongly overlap with zero ($-20$ to $33$). Thus, it looks as if the groups would not differ from each other any more. At the same time, we see that the predictor variable IQ shows a negative effect (Estimate = $-1$ with 95\% confidence interval: $-1.7$ to $-0.4$), suggesting that - as expected - response times seem to be faster in subjects with higher IQ.
```{r figRTFIQ, fig=TRUE, include=TRUE, echo=FALSE, cache=FALSE, message=FALSE, warning=FALSE, fig.width=4.5, fig.height=3, fig.cap = "Response times as a function of individual IQ for two groups with a lexical decision training (F2) versus a control training (F1). Points indicate individual subjects, and lines with error bands indicate linear regression lines."}
(plot_RT_IQ <- ggplot(data = df_contrasts5, aes(x = IQ, y = RT, colour = F, linetype = F)) +
geom_point() +
geom_smooth(method = "lm") +
labs(y = "Response times [ms]"))
```
This result can also be seen in Figure\ \@ref(fig:figRTFIQ), which shows that response times decrease with increasing IQ, as suggested by the linear model. However, the heights of the two regression lines do not differ from each other, consistent with the observation in the brms model that the effect of factor F did not seem to differ from zero. That is, factor F in the linear model estimates the difference in height of the regression line between both groups.
That the height does not differ and the effect of F is estimated close to zero suggests that in fact group F2 showed faster response times not because of their additional training program. Instead, they had faster response times simply because their IQ was by chance higher on average compared to the control group F1. This analysis is called "analysis of covariance" (ANCOVA), where it's possible to test a group-difference after "controlling for" the influence of a covariate.
Importantly, we can see in Figure\ \@ref(fig:figRTFIQ) that the two regression lines for the two groups are exactly parallel to each other. That is, the influence of IQ on response times seems to be exactly the same in both groups. This is actually a prerequiste for the ANCOVA analysis that needs to be checked in the data. That is, if we want to test the difference between groups after controlling for a covariate (here IQ), we have to test whether the influence of the covariate is the same in both groups. We can investigate this by including an interaction term between the factor and the covariate in the brms model:
```{r, echo=TRUE, message=FALSE, warning=FALSE, error=FALSE, results="hide"}
fit_RT_FxIQ <- lm(RT ~ 1 + F * IQ.c,
data = df_contrasts5
)
```
```{r, echo=TRUE}
round(summary(fit_RT_FxIQ)$coefficients, 2)
```
The estimate for the interaction (the term "F1:IQ.c") is very small here (close to 0) and the 95\% confidence intervals clearly overlap with zero, showing that the two regression lines are estimated to be very similar, or parallel, to each other. If this is the case, then it is possible to correct for IQ when testing the group difference.
### Estimating differences in slopes
We now take a look at a different data set.
```{r, echo=TRUE}
data("df_contrasts6")
levels(df_contrasts6$F) <- c("simple", "complex")
str(df_contrasts6)
```
This again contains data from response times (RT) in two groups. Let's assume the two groups have performed two different response time tasks, where one simple RT task doesn't rely on much cognitive processing (group "simple"), whereas the other task is more complex and depends on complex cognitive operations (group "complex"). We therefore expect that RTs in the simple task should be independent of IQ, whereas in the complex task, individuals with a high IQ should be faster in responding compared to individuals with low IQ. Thus, our primary hypothesis of interest states that the influence of IQ on RT differs between conditions. This means that we are interested in the difference between slopes. A slope in a linear regression assesses how strongly the dependent variable (here RT) changes with an increase of one unit on the covariate (here IQ), it thus assesses how "steep" the regression line is. Our research hypothesis is that the regression lines differ between groups.
```{r figRTFxIQ, fig=TRUE, include=TRUE, echo=FALSE, cache=FALSE, message=FALSE, warning=FALSE, fig.width=4.5, fig.height=3, fig.cap = "Response times as a function of individual IQ for two groups performing a simple versus a complex task. Points indicate individual subjects, and lines with error bands indicate linear regression lines."}
(plot_RTxIQ <- ggplot(data = df_contrasts6, aes(x = IQ, y = RT, colour = F, linetype = F)) +
geom_point() +
geom_smooth(method = "lm") +
labs(y = "Response times [ms]"))
```
The results, displayed in Figure\ \@ref(fig:figRTFxIQ), suggest that the data are consistent with our research hypothesis. For the subjects performing the complex task, response times seem to decrease with increasing IQ, whereas for subjects performing the simple task, response times seem to be independent of IQ. As stated before, our primary hypothesis relates to the difference in slopes. Statistically speaking, this is assessed in the interaction between the factor and the covariate. Thus, we run a linear model where the interaction is included. Importantly, we first use scaled sum contrasts for the group effect, and again center the covariate IQ.
```{r, echo=TRUE, message=FALSE, warning=FALSE, error=FALSE, results="hide"}
contrasts(df_contrasts6$F) <- c(-0.5, +0.5)
df_contrasts6$IQ.c <- df_contrasts6$IQ - mean(df_contrasts6$IQ)
fit_RT_FxIQ2 <- lm(RT ~ 1 + F * IQ.c,
data = df_contrasts6
)
```
```{r, echo=TRUE}
round(summary(fit_RT_FxIQ2)$coefficients, 2)
```
We can see that the main effect of IQ (term "IQ.c") is negative ($-0.8$) with 95\% confidence intervals $-1.5$ to $-0.2$, suggesting that overall response times decrease with increasing IQ. However, this is qualified by the interaction term, which is estimated to be negative ($-1.6$), with 95\% confidence intervals $-2.9$ to $-0.3$. This suggests that the slope in the complex group (which was coded as $+0.5$ in the scaled sum contrast) is more negative than the slope in the simple group (which was coded as $-0.5$ in the scaled sum contrast). Thus, the interaction assesses the difference between slopes.
We can also run a model where the simple slopes are estimated, i.e., the slope of IQ in the simple group and the slope of IQ in the complex group. This can be implemented by using the nested coding that we learned about in the previous section:
```{r, echo=TRUE, message=FALSE, warning=FALSE, error=FALSE, results="hide"}
fit_RT_FnIQ2 <- lm(RT ~ 1 + F / IQ.c,
data = df_contrasts6
)
```
```{r, echo=TRUE}
round(summary(fit_RT_FnIQ2)$coefficients, 2)
```
Now we see that the slope of IQ in the simple group ("Fsimple:IQ.c") is estimated to be $0$, with confidence intervals clearly including zero. By contrast, the slope in the complex group ("Fcomplex:IQ.c") is estimated as $-1.6$ (95\% confidence interval $-2.5$ to $-0.7$). This is consistent with our hypothesis that high IQ speeds up response times for the complex but not for the simple task.
We can also see from the nested analysis that the difference in slopes between conditions is $-1.6 - 0.0 = -1.6$. This is exactly the value for the interaction term that we estimated in the previous model, demonstrating that interaction terms assess the difference between slopes; i.e., they estimate the extent to which the regression lines in the two conditions are parallel, with an estimate of 0 indicating perfectly parallel lines.
A note: It is very important to always center covariates before including them into a model. If covariates are not centered, then the main effects (here the main effect for the factor) cannot be interpreted as main effects any more.
Interestingly, one can also do analyses with interactions between a covariate and a factor, but by using different contrast codings. For example, if we use treatment contrasts for the factor, then the main effect of IQ.c assess not the average slope of IQ.c across conditions, but instead the nested slope of IQ.c within the baseline group of the treatment contrast. The interaction still assesses the difference in slopes between groups. In a situation where there are more than two groups, when one estimates the interaction of contrasts with a covariate, then the contrasts define which slopes are compared with each other in the interaction terms. For example, when using sum contrasts in an example where the influence of IQ is measured on response times for nouns, verbs, and adjectives, then there are two interaction terms: these assess (1) whether the slope of IQ for nouns is different from the average slope across conditions, and (2) whether the slope of IQ for verbs is different from the average slope across conditions. If one uses repeated contrasts in a situation where the influence of IQ on response times is estimated for word frequency conditions "low", "medium-low", "medium-high", and "high", then there are three interaction terms (one for each contrast). The first interaction term estimates the difference in slopes between "low" and "medium-low" word frequencies, the second interaction term estimates the difference in slopes between "medium-low" and "medium-high" word frequencies, and the third interaction term estimates the difference in slopes between "medium-high" and "high" word frequency conditions. Thus, the logic of how contrasts specify certain comparisons between conditions extends directly to the situation where differences in slopes are estimated.
## Interactions in generalized linear models (with non-linear link functions) {#sec:interactions:NLM}
We next look at generalized linear models, where a linear predictor is passed through a non-linear link function to predict the dependent variable. Examples for generalized linear models include logistic regression models and models assuming a log-normal or a Poisson distribution. Here, we treat an example with a logistic model in a 2 x 2 factorial between-subject design. The logistic model has the following non-linear link function: $p(y=1 \mid x, b) = \frac{1}{1 + \exp(-\eta)}$, where $\eta$ is the latent linear predictor. For example, in our 2 x 2 factorial design with main effects A and B and their interaction, $\eta$ is computed as a linear combination of the intercept plus the main effects and their interaction: $\eta = 1 + \beta_A x_A + \beta_B x_B + \beta_{A \times B} x_{A \times B}$.
Thus, there is a latent level of linear predictions ($\eta$), which are then passed through a non-linear link function to predict the probability that the observed data is a success ($p(y = 1)$). We will use this logistic model to analyze an example data set where the dependent variable is dichotomous, coded as either a 1 (indicating success) or a 0 (indicating failure).
We load a simulated data set where the dependent variable codes whether a subject performed a task successfully (pDV = 1) or not (pDV = 0). Moreover, the data set has two between-subject factors A and B. The means and frequentist 95\% confidence intervals for each of the four conditions are shown in Table\ \@ref(tab:cTab7Means).
```{r}
data("df_contrasts7")
str(df_contrasts7)
```
```{r cTab7Means, echo=FALSE, message=FALSE, warning=FALSE, results = "asis"}
table7 <- df_contrasts7 %>% group_by(A, B) %>% # plot interaction
dplyr::summarize(N = length(pDV), M = mean(pDV))
GM <- mean(table7$M) # Grand Mean
table7a <- as.data.frame(table7)
names(table7a) <- c(
"Factor A", "Factor B", "N data",
"Means"
)
# apa_table(table7a, placement="b", digits=2,
# caption="Summary statistics per condition for the simulated data.")
kbl(table7a, booktabs = T, vline = "", position = "h", digits = 2, caption = "Summary statistics per condition for the simulated data.") # format="latex",
```
To analyze this data, we use scaled sum contrasts, as we had done above for the $2 \times 2$ design with response times as the dependent variable, and which allow us to interpret the main effects as main effects. Next, we fit a linear model. The model specification is the same as the model with response times - with two differences: First, the `family` argument is now specified as `family = binomial(link = "logit")` to indicate the logistic model.
```{r, echo=TRUE, message=FALSE, warning=FALSE, error=FALSE, results="hide"}
contrasts(df_contrasts7$A) <- c(-0.5, +0.5)
contrasts(df_contrasts7$B) <- c(-0.5, +0.5)
# GLM
fit_pDV_AB.sum <- glm(pDV ~ 1 + A * B,
data = df_contrasts7,
family = binomial(link = "logit")
)
```
```{r, echo=TRUE}
round(summary(fit_pDV_AB.sum)$coefficients, 2)
```
The results from this analysis show that the estimates for the two main effects ("A1" and "B1") as well as the interaction ("A1:B1") are positive and the 95\% confidence intervals do not include zero. We could now proceed to perform likelihood ratio tests to investigate the evidence that there is for each of the effects.
## Summary
To summarize, we have seen interesting results for contrasts in the context of $2 \times 2$ designs, where depending on the contrast coding, the factors estimated nested effects (treatment contrasts) or main effects (sum contrasts). We also saw that it is possible to code contrasts for a $2 \times 2$ design, by creating one large factor comprising all design cells, and by specifying all effects of interest in one large contrast matrix. In designs with one factor and one covariate it is possible to control group differences for differences in the covariate (ANCOVA), or to test whether regression slopes are parallel in different experimental conditions. Finally, contrast coding in generalized linear models works the same way as in the standard linear model.
## Exercises {#sec:Contrasts2x2exercises}
```{exercise, Contrasts2x2PersianANOVA}
ANOVA coding for a four-condition design.
```
Load the following data. These data are from Experiment 1 in a set of reading studies on Persian [@SafaviEtAlFrontiers2016]; we encountered these data in the preceding chapter's exercises.
```{r}
library(lingpsych)
data("df_persianE1")
dat1 <- df_persianE1
head(dat1)
```
The four conditions are:
- Distance=short and Predictability=unpredictable
- Distance=short and Predictability=predictable
- Distance=long and Predictability=unpredictable
- Distance=long and Predictability=predictable
For the data given above, define an ANOVA-style contrast coding, and compute main effects and interactions. Check with `hypr` what the hypothesis tests are with an ANOVA coding, and write down the null hypotheses.
```{exercise, Contrasts2x2x2Dillon2013}
ANOVA and nested comparisons in a $2\times 2\times 2$ design.
```
Load the following data-set. This is $2\times 2\times 2$ design from @jager2020interference, with the factors Grammaticality (grammatical vs. ungrammatical), Dependency (Agreement vs.\ Reflexives), and Interference (Interference vs.\ no interference). The experiment is a replication attempt of Experiment 1 reported in @Dillon-EtAl-2013.
```{r}
library(lingpsych)
data("df_dillonrep")
```
- The grammatical conditions are a,b,e,f. The rest of the conditions are ungrammatical.
- The agreement conditions are a,b,c,d. The other conditions are reflexives.
- The interference conditions are a,d,e,h, and the others are the no-interference conditions.
The dependent measure of interest is TFT (total fixation time, in milliseconds).
Using a linear model, do a main effects and interactions ANOVA contrast coding, and obtain an estimate of the main effects of Grammaticality, Dependency, and Interference, and all interactions. You may find it easier to code the contrasts coding the main effects as +1, -1, using `ifelse` in R to code vectors corresponding to each main effect. This will make the specification of the interactions easy.
The researchers had a further research hypothesis: in ungrammatical sentences only, agreement would show an interference effect but reflexives would not. In grammatical sentences, both agreement and reflexives are expected to show interference effects. This kind of research question can be answered with nested contrast coding.
To carry out the relevant nested contrasts, define contrasts that estimate the effects of
- grammaticality
- dependency type
- the interaction between grammaticality and dependency type
- reflexives interference within grammatical conditions
- agreement interference within grammatical conditions
- reflexives interference within ungrammatical conditions
- agreement interference within ungrammatical conditions
Do the estimates match expectations? Check this by computing the condition means and checking that the estimates from the models match the relevant differences between conditions or clusters of conditions.
```{exercise, Contrasts2x2Smith2020}
Another ANOVA comparison in a $2\times 2\times 2$ design.
```
Hypothesis testing can be a very fragile business. One situation that sometimes occurs is that a few influential data points can change the result from significant to non-significant. An example is a self-paced reading experiment (Experiment 1) by @smith2021encoding. This is a $2\times 2$ design, with a factor called N2Factor with two levels representing the number marking on the second of two nouns in the sentence, and another factor called SemFactor representing the semantic similarity of the two nouns in the sentence. The data are from the critical region in the sentence (a verb), in milliseconds. The expectation is that when the two nouns are similar, reading times are slower at the critical region.
```{r}
library(lingpsych)
data("df_smithE1")
head(df_smithE1)
```
First, fit a linear mixed model using an ANOVA contrast coding, and determine whether there is a main effect of semantic similarity. Then refit the model, removing all the data points that are larger than 3000 milliseconds and reassess the main effect of semantic similarity. This should remove 9 data points out of 3441 data points. Does the significant effect of similarity disappear?