Repository navigation
Expand file tree
/
Copy path08-Simulation.Rmd
More file actions
861 lines (671 loc) · 30.1 KB
/
Copy path08-Simulation.Rmd
File metadata and controls
861 lines (671 loc) · 30.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
# Using simulation to understand your model
Data analysis is often taught as if the goal is to work out the p-value and make a decision: reject or fail to reject the null hypothesis. However, understanding the long-run properties of one's experiment design and statistical model under repeated sampling requires more work and thought. Specifically, it is important to understand (a) what one's model's power and Type I error properties are, and (b) whether the model we plan to fit to our data can, even in principle, recover the parameters in the model.
In order to study these properties of one's model, it is necessary to learn to simulate data that reflects our experimental design.
Let's think about how to simulate data given a Latin-square $2$ condition repeated measures design. We begin with our familiar running example, the @grodner English relative clause data.
## A reminder: The maximal linear mixed model
Recall the structure of the linear mixed model that can be used to fit the @grodner data. We will discuss the so-called maximal model here---varying intercepts and slopes for subject and for item, with correlations---because that is the most general case.
In the model specification below, $i$ indexes subjects, $j$ items. The vector `so` has the sum contrast coding as usual: object relatives are coded as +1/2 and subject relatives as -1/2. We use this coding instead of $\pm 1$ as before, because now the slope will reflect the effect size rather than two times the effect size (see the hypothesis testing chapter).
Every row in the data-frame can be uniquely identified by the subject and item id, because this is a Latin square design and each subject sees exactly one instance of each item in a particular condition.
\begin{equation}
y_{ij} = \beta_0 + u_{0i} + w_{0j} + (\beta_1 + u_{1i} + w_{1j}) \times so_{ij} + \varepsilon_{ij}
\end{equation}
where $\varepsilon_{ij} \sim Normal(0,\sigma)$ and
\begin{equation}\label{eq:covmatsimulations}
\Sigma_u
=
\begin{pmatrix}
\sigma _{u0}^2 & \rho _{u}\sigma _{u0}\sigma _{u1}\\
\rho _{u}\sigma _{u0}\sigma _{u1} & \sigma _{u1}^2\\
\end{pmatrix}
\quad
\Sigma _w
=
\begin{pmatrix}
\sigma _{w0}^2 & \rho _{w}\sigma _{w0}\sigma _{w1}\\
\rho _{w}\sigma _{w0}\sigma _{w1} & \sigma _{w1}^2\\
\end{pmatrix}
\end{equation}
\begin{equation}\label{eq:jointpriordistsimulation}
\begin{pmatrix}
u_0 \\
u_1 \\
\end{pmatrix}
\sim
\mathcal{N} \left(
\begin{pmatrix}
0 \\
0 \\
\end{pmatrix},
\Sigma_{u}
\right),
\quad
\begin{pmatrix}
w_0 \\
w_1 \\
\end{pmatrix}
\sim
\mathcal{N}\left(
\begin{pmatrix}
0 \\
0 \\
\end{pmatrix},
\Sigma_{w}
\right)
\end{equation}
$\beta_0$ and $\beta_1$ are the intercept and slope, representing the grand mean and the deviation from the grand mean in each condition. $u$ are the subject level adjustments, and $w$ the item level adjustments to the intercept and slope.
The above mathematical model expresses a generative process. In order to produce simulated data using the above process, we have to decide on some parameter values. We do this by estimating the parameters from the @grodner study.
## Obtain estimates from a previous study
First we load and prepare the relative clause data for data analysis.
```{r}
gg05e1 <- read.table("data/grodnergibsonE1crit.txt", header = TRUE)
gg05e1$so <- ifelse(gg05e1$condition == "objgap", 1 / 2, -1 / 2)
gg05e1$logrt <- log(gg05e1$rawRT)
```
Next, fit the so-called maximal model. We will ignore the singularity warning as it won't affect us in our simulations.
```{r}
library(lme4)
m <- lmer(logrt ~ so +
(1 + so | subject) +
(1 + so | item),
data = gg05e1,
## "switch off" warnings:
control = lmerControl(calc.derivs = FALSE)
)
```
The model summary shows that we can reject the null hypothesis of no difference in relative clauses:
```{r}
summary(m)$coefficients
```
Let's focus on that effect for our power analysis. What is the prospective power of detecting this effect *for a future study*? Note that we never compute power for an existing study---that is called post-hoc power and is a pointless quantity to compute because once the p-value is known, the power is just a transformation of the p-value [@hoenigheisey].
What we are doing below will *look* like post-hoc power because we are using existing data to compute power. However, what is crucially different in our approach is that (a) we remain unsure about the true effect, (b) we are making a statement about what the power properties would be *if we ran the same study again*, with new subjects, but in the same environment (lab, etc.). We are not making any claim about the power properties of the *current* experiment; that ship has already sailed, the data are already at hand! Once the data are analyzed, it's too late to compute power for that particular data-set. A power analysis is only relevant for a design to be run in the future.
## Decide on a range of plausible values of the effect size
Notice that the effect in milliseconds is relatively large, given the estimates from similar phenomena in reading studies in psycholinguistics [@JaegerEngelmannVasishth2017]:
```{r}
b0 <- summary(m)$coefficients[1, 1]
b1 <- summary(m)$coefficients[2, 1]
## effect estimate in log ms:
b1
## effect estimate in ms:
exp(b0 + b1 * (0.5)) - exp(b0 + b1 * (-0.5))
```
But the standard errors tell us that the effect could be as small or as large as the following values:
```{r}
b1_stderr <- summary(m)$coefficients[2, 2]
lower <- b1 - 2 * b1_stderr
upper <- b1 + 2 * b1_stderr
lower
upper
```
The above range `r round(lower,2)` and `r round(upper,2)` arises because the range of plausible effect sizes is between $\hat\beta_1 \pm 2SE$ on the log ms scale.
On the ms scale, the range is:
```{r}
exp(b0 + lower * (0.5)) - exp(b0 + lower * (-0.5))
exp(b0 + upper * (0.5)) - exp(b0 + upper * (-0.5))
```
On the ms scale we see that that's a *lot* of uncertainty in the effect size! With some experience, you will come to recognize that such a wide confidence bound is a sign of low power. We will just establish the prospective power properties of this study in a minute.
We can take the above uncertainty of the $\hat\beta_1$ estimator into account (on the log ms scale---remember that the model is based on log rt) by assuming that the effect has the following uncertainty on the log ms scale:
\begin{equation}
\beta_1 \sim Normal(0.12,0.05)
\end{equation}
Here, we are doing something that is, strictly speaking, Bayesian in thinking. We are describing our uncertainty about the true effect from the best estimate we have---existing data. To talk about the uncertainty, we are (ab)using the 95\% confidence interval (treating it like its telling us the range of plausible values). Recall that strictly speaking, in the frequentist paradigm, one cannot talk about the probability distribution of the effect size---in frequentist theory, the true value of the parameter is a point value, it has no distribution. The range $\hat\beta_1 \pm 2\times SE$ refers to the estimated mean of the sampling distribution of the sample means, and to the standard deviation of this sampling distribution. Thus, strictly speaking, this range does not reflect our uncertainty about the true parameter's value. Having said this, we are going to use the effect estimates from our model fit as a starting point for our power analysis because this is the best information we have so far about the English relative clause design.
## Extract parameter estimates
Next, in preparation for the power analysis, we extract all the parameter estimates from the model we have fit above. The parameters are:
- The two fixed effects (the $\beta$ parameters)
- The residuals' standard deviation
- The standard deviations of the subject intercept and slope adjustments, and the corresponding correlation matrix.
- The standard deviations of the item intercept and slope adjustments, and the corresponding correlation matrix.
The correlation matrices and the subject/item random effects standard deviations are used to assemble the variance covariance matrix; this is done using the `sdcor2cov` function from the `SIN` package; recall the discussion in chapter 1. For the variance covariance matrix for items random effects, we use an intermediate value of 0.5 for the correlation parameter because the linear mixed model was unable to estimate the parameter.
```{r}
m <- lmer(logrt ~ so +
(1 + so | subject) +
(1 + so | item),
data = gg05e1,
## "switch off" warnings:
control = lmerControl(calc.derivs = FALSE)
)
## extract parameter estimates:
beta <- round(summary(m)$coefficients[, 1], 4)
sigma_e <- round(attr(VarCorr(m), "sc"), 2)
subj_ranefsd <- round(attr(VarCorr(m)$subject, "stddev"), 4)
subj_ranefcorr <- round(attr(VarCorr(m)$subject, "corr"), 1)
## assemble variance-covariance matrix for subjects:
Sigma_u <- SIN::sdcor2cov(
stddev = subj_ranefsd,
corr = subj_ranefcorr
)
item_ranefsd <- round(attr(VarCorr(m)$item, "stddev"), 4)
item_ranefcorr <- round(attr(VarCorr(m)$item, "corr"), 1)
## assemble variance matrix for items:
## choose some intermediate values for correlations:
corr_matrix <- (diag(2) + matrix(rep(1, 4), ncol = 2)) / 2
Sigma_w <- SIN::sdcor2cov(
stddev = item_ranefsd,
corr = corr_matrix
)
```
## Define a function for generating data
Next, we define a function that generates repeated measures data given the parameter estimates. The basic idea here is the following.
- First, create a data-frame that represents a Latin-square design.
- Then, given the condition id, and the subject and item ids in each row of the data frame, generate data row-by-row.
We explain these steps next.
### Generate a Latin-square design
First, consider how one can create a Latin-square design. Suppose we have four items and four subjects. For such an experiment, we would create two groups, g1 and g2, with the following layout.
```{r}
nitem <- 4
nsubj <- 4
g1 <- data.frame(
item = 1:nitem,
cond = rep(c("a", "b"), nitem / 2)
)
g2 <- data.frame(
item = 1:nitem,
cond = rep(c("b", "a"), nitem / 2)
)
g1
g2
```
Half the total number of subjects will be assigned to group 1 and half to group 2:
```{r}
## assemble data frame:
gp1 <- g1[rep(
seq_len(nrow(g1)),
nsubj / 2
), ]
gp2 <- g2[rep(
seq_len(nrow(g2)),
nsubj / 2
), ]
simdat <- rbind(gp1, gp2)
## add subject column:
simdat$subj <- rep(1:nsubj, each = nitem)
```
Finally, the contrast coding for each row in the data-frame is set up:
```{r}
## add contrast coding:
simdat$so <- ifelse(simdat$cond == "a", -1 / 2, 1 / 2)
```
### Generate data row-by-row
Then, we proceed row-by-row in this data frame, and generate data for each subject, item, and condition. For example, the first row of our simulated data-set has subject id:
```{r}
simdat[1, ]$subj
```
Similarly, the first row has item id:
```{r}
simdat[1, ]$item
```
The first row's condition coding is:
```{r}
simdat[1, ]$so
```
These three pieces of information are what we need to generate data for the first row. Recall that the model for subject $i$ and item $j$ in condition `so` is
\begin{equation}
\beta_0 + u_{0i} + w_{0j} + (\beta + u_{1i} + w_{1j})\times so + \varepsilon \hbox{ where } \varepsilon \sim N(0,\sigma)
\end{equation}
The terms u0, w0, and u1, w1, which are the adjustments to the intercepts and slopes by subject and item, are stored in two matrices that are generated randomly each time that we simulate new subjects/items. Recall from chapter 1 how bivariate data are generated. The intercept and slope adjustments will be generated using the `mvrnorm` function in the MASS library. For example, given the variance covariance matrix for subjects `Sigma_u` that we created above, the subject random effects (intercept and slope adjustments) for 10 subjects can be generated in a matrix as follows:
```{r}
library(MASS)
u <- mvrnorm(
n = 10,
mu = c(0, 0), Sigma = Sigma_u
)
u
```
Each row in this matrix is the intercept and slope adjustment for a subject; the row number indexes the subject id. For example, subject 1's intercept adjustment is:
```{r}
u[1, 1]
```
Subject 1's slope adjustment is:
```{r}
u[1, 2]
```
Analogously to the subject random effects matrix, a matrix for items random effects is also generated. As an example, we generate simulated random effects for 10 items:
```{r}
w <- mvrnorm(
n = 10,
mu = c(0, 0), Sigma = Sigma_w
)
w
```
Now, to generate simulated data for subject 1 and item 1 for object relatives, we simply need to run this line of code:
```{r}
rlnorm(
1, beta[1] + u[1, 1] + w[1, 1] +
(beta[2] + u[1, 2] + w[1, 2]) * (0.5),
sigma_e
)
```
For subject 2, all that would change is the subject id: instead of `u[1,1]`, and `u[1,2]` we would write `u[2,1]` and `u[2,2]`. The for-loop below works through the `simdat` data-frame row by row, looks up the subject id, the item id for that row, and the condition coding for that row, and fills in the simulated reading time using the above code. This is how the simulated data are generated.
Here is the complete function for generating simulated data. It uses all the bits of code we discussed above.
```{r}
library(MASS)
## assumes that no. of subjects and
## no. of items is divisible by 2.
gen_sim_lnorm2 <- function(nitem = 16,
nsubj = 42,
beta = NULL,
Sigma_u = NULL, # subject vcov matrix
Sigma_w = NULL, # item vcov matrix
sigma_e = NULL) {
## prepare data frame for a two-condition latin square:
g1 <- data.frame(
item = 1:nitem,
cond = rep(c("a", "b"), nitem / 2)
)
g2 <- data.frame(
item = 1:nitem,
cond = rep(c("b", "a"), nitem / 2)
)
## assemble data frame:
gp1 <- g1[rep(
seq_len(nrow(g1)),
nsubj / 2
), ]
gp2 <- g2[rep(
seq_len(nrow(g2)),
nsubj / 2
), ]
simdat <- rbind(gp1, gp2)
## add subject column:
simdat$subj <- rep(1:nsubj, each = nitem)
## add contrast coding:
simdat$so <- ifelse(simdat$cond == "a", -1 / 2, 1 / 2)
## subject random effects:
u <- mvrnorm(
n = length(unique(simdat$subj)),
mu = c(0, 0), Sigma = Sigma_u
)
## item random effects
w <- mvrnorm(
n = length(unique(simdat$item)),
mu = c(0, 0), Sigma = Sigma_w
)
## generate data row by row:
N <- dim(simdat)[1]
rt <- rep(NA, N)
for (i in 1:N) {
rt[i] <- rlnorm(
1, beta[1] +
u[simdat[i, ]$subj, 1] +
w[simdat[i, ]$item, 1] +
(beta[2] + u[simdat[i, ]$subj, 2] +
w[simdat[i, ]$item, 2]) * simdat$so[i],
sigma_e
)
}
simdat$rt <- rt
simdat$subj <- factor(simdat$subj)
simdat$item <- factor(simdat$item)
simdat
}
```
Let's generate some simulated data and check what the data look like:
```{r}
dat <- gen_sim_lnorm2(
nitem = 16,
nsubj = 42,
beta = beta,
Sigma_u = Sigma_u,
Sigma_w = Sigma_w,
sigma_e = sigma_e
)
```
The data have the expected structure:
```{r}
## fully crossed subjects and items:
head(t(xtabs(~ subj + item, dat)))
## 8 measurements per condition:
head(t(xtabs(~ subj + cond, dat)))
## contrast coding check:
xtabs(~ so + cond, dat)
## condition b is slower than a:
round(with(dat, tapply(rt, cond, mean)))
```
Everything checks out.
## Repeated generation of data to compute power
With the function for simulating data ready, we are now able to repeatedly generate simulated data. Next, we generate data 100 times, fit a linear mixed model each time, and extract the t-value from each linear mixed model fit. The vector t-values is then used to compute power: we simply look at the proportion of absolute t-values that exceed the value 2.
```{r cache=TRUE,message=FALSE,warning=FALSE}
nsim <- 100
sotval <- rep(NA, nsim)
for (i in 1:nsim) {
# generate sim data:
dat <- gen_sim_lnorm2(
nitem = 16,
nsubj = 42,
beta = beta,
Sigma_u = Sigma_u,
Sigma_w = Sigma_w,
sigma_e = sigma_e
)
## fit model to sim data:
m <- lmer(log(rt) ~ so + (1 + so | subj) + (1 + so | item), dat,
control = lmerControl(calc.derivs = FALSE)
)
## extract the t-value
sotval[i] <- summary(m)$coefficients[2, 3]
}
pow <- mean(abs(sotval) > 2)
```
The power estimate from the above code is `r round(pow,2)`.
The following computation will take a lot of time because we are generating and fitting data $3\times 100$ times.
Here, we will assume that the true effect has the following range of plausible values:
```{r}
## lower bound:
.12 - 2 * .05
## mean
.12
## upper bound
.12 + 2 * .05
```
We will run two for-loops now: the first for-loop selects one of the plausible values as the value for the slope, and then the second for-loop runs 100 simulations to compute power for that effect size.
This time, instead of ignoring convergence problems, we can record the proportion of times that we get a convergence failure or problem, and we can discard that result:
```{r cache=TRUE,message=FALSE,warning=FALSE}
nsim <- 100
## effect size possibilities:
b1_est <- c(0.02, 0.12, 0.22)
sotvals <- matrix(rep(NA, nsim * length(b1_est)), ncol = nsim)
failed <- matrix(rep(0, nsim * length(b1_est)), ncol = nsim)
for (j in 1:length(b1_est)) {
for (i in 1:nsim) {
beta[2] <- b1_est[j]
dat_sim <- gen_sim_lnorm2(
nitem = 16,
nsubj = 42,
beta = beta,
Sigma_u = Sigma_u,
Sigma_w = Sigma_w,
sigma_e = sigma_e
)
## no correlations estimated to
## minimize convergence problems:
## analysis done after log-transforming:
m <- lmer(log(rt) ~ so + (so || subj) +
(so || item),
data = dat_sim,
control = lmerControl(calc.derivs = FALSE)
)
## ignore failed trials
if (any(grepl("failed to converge", m@optinfo$conv$lme4$messages)) ||
any(grepl("boundary", m@optinfo$conv$lme4$messages))) {
failed[j, i] <- 1
} else {
sotvals[j, i] <- summary(m)$coefficients[2, 3]
}
}
}
```
You can examine the proportion of failed convergences:
```{r}
## proportion of convergence failures:
rowMeans(failed)
```
Power can now be computed for each effect size:
```{r cache=TRUE}
pow <- rep(NA, length(b1_est))
for (k in 1:length(b1_est)) {
pow[k] <- mean(abs(sotvals[k, ]) > 2, na.rm = TRUE)
}
```
The power estimate for the lower bound of the $\beta_1$ estimate is `r round(pow[1],2)`, and for the upper bound is `r round(pow[3],2)`. The power estimate for the mean estimate of $\beta_1$ is `r round(pow[2],2)`.
Notice that there is a lot of uncertainty about the power estimate here!
Recall that power is a **function** of
- effect size
- standard deviation(s); in linear mixed models, these are all the variance components and the correlations
- sample size (numbers of subjects and items)
In papers, you will often see text like "power was x%". This statement reflects a misunderstanding; power is best plotted as a function of (a subset of) these variables.
In the discussion above, we display a range of power estimates; this range reflects our uncertainty about the power estimate as a function of the plausible effect sizes. Often (as here) this uncertainty will be very high! I.e., given what one knows so far, it may be difficult to pin down what the assumed effect size etc., should be, and that makes it hard to give a precise range for your power estimate.
## What you can now do
Given the above code and workflow, you can now figure out how many subjects you might need to achieve 80% power, assuming a certain effect size (or a range of effect sizes as above) and assuming some specific values for the standard deviations and variance covariance matrices.
You can also study Type I error properties of your model as a function of whether the model is a maximal model or a varying intercepts only model.
Example: Compute power as a function of effect size and sample size. Note that the number of subjects has to be even, otherwise the simulation code will fail! One could put in a test for this in the code: if the number of subjects is divisible by 2, the modulo function should return 0:
```{r}
10 %% 2
11 %% 2
```
```{r}
## define a function for computing power
## (as a function of effect size and
## subject sample size:
compute_power <- function(b = NULL, nsubjects = 28) {
if (nsubjects %% 2 != 0) {
stop("No. of subjects must be divisible by 2.")
}
nsim <- 100
sotvals <- rep(NA, nsim)
failed <- rep(0, nsim)
for (i in 1:nsim) {
beta[2] <- b
dat_sim <- gen_sim_lnorm2(
nitem = 24,
nsubj = nsubjects,
beta = beta,
Sigma_u = Sigma_u,
Sigma_w = Sigma_w,
sigma_e = sigma_e
)
## no correlations estimated to avoid convergence problems:
## analysis done after log-transforming:
m <- lmer(log(rt) ~ so + (so || subj) +
(so || item), data = dat_sim, control = lmerControl(calc.derivs = FALSE))
## ignore failed trials
if (any(grepl("failed to converge", m@optinfo$conv$lme4$messages))) {
failed[i] <- 1
} else {
sotvals[i] <- summary(m)$coefficients[2, 3]
}
}
## power:
paste("Power:", round(mean(abs(sotvals) > 2,
na.rm = TRUE
), 2), sep = " ")
}
```
```{r message=FALSE,warning=FALSE,results="asis"}
## usage: this will halt function
## with an error message
# compute_power(b=0.03,nsubjects=29)
compute_power(b = 0.03, nsubjects = 28)
```
## Using the package `designr` to simulate data and compute power
There are major advantages to writing one's own code for generating repeated measures data: one can control exactly what one considers to be the generative process, and one can obtain a deeper understanding of how the linear mixed model is set up. However, for certain standard experimental designs, one can use pre-defined functions for simulating data. The advantage of using such packages is that one can abstract away from the implementation details; but this can also be a disadvantage because one might end up simulating data without really understanding the assumptions behind the data-generative process.
An R package, `designr`, provides some built-in functions that can simplify the process of computing power for standard repeated measures designs. For example, consider again the two-condition design involving English relative clauses that we saw earlier [@grodner].
### Simulating data with two conditions
First, load the data, and prepare the contrast coding and log-transform the reading times.
```{r}
gg05e1 <- read.table("data/grodnergibsonE1crit.txt", header = TRUE)
gg05e1$so <- ifelse(gg05e1$condition == "objgap", 1 / 2, -1 / 2)
gg05e1$logrt <- log(gg05e1$rawRT)
```
Next, we fit a linear mixed model to the data. As an example, we use raw reading times on the millisecond scale.
```{r}
## frequentist analysis:
library(lme4)
m_lmer <- lmer(rawRT ~ so + (1 + so | subject) + (1 + so | item), gg05e1,
control = lmerControl(calc.derivs = FALSE)
)
summary(m_lmer)
```
The correlations between the varying intercepts and slopes could not be estimated, so the model is over-parameterized. We can refit the model without correlations:
```{r}
m_lmer <- lmer(rawRT ~ so + (1 + so || subject) + (1 + so || item), gg05e1)
summary(m_lmer)
```
Next, we generate a data-frame through the `designr` package, with the same design as the data used above:
```{r}
library(designr)
## example
## define data frame:
design <- fixed.factor("so", levels = c("subjgap", "objgap")) +
random.factor("subject", instances = 42) +
random.factor("item", instances = 16)
dat <- design.codes(design)
dat$so <- ifelse(dat$so == "objgap", 1 / 2, -1 / 2)
head(dat)
```
To compute prospective power based on the estimates from the English relative clause data, the following for-loop is run. In each iteration, data is first generated using the design set up above; this is done using the `simLMM` function from the `designr` package. Notice here that a "maximal" model is specified, but the correlations are set to zero (CP=0.0); this has the effect that the data generated assume no correlation between the intercept and slope for subjects and items. Having generated the data, the `lmer` function is used to fit the model to the simulated data, and then the t-value of the slope is saved. This t-value can then be used to compute power in the usual way.
```{r cache=TRUE,warning=FALSE,message=FALSE}
tvals <- rep(NA, 100)
for (i in 1:100) {
## generate data:
dat$ysim <- simLMM(
formula = ~ 1 + so + (1 + so | subject) +
(1 + so | item),
data = dat,
LMM = m_lmer,
CP = 0.0,
empirical = FALSE, verbose = FALSE,
family = "gaussian"
)
## fit model to simulated data:
m <- lme4::lmer(ysim ~ so + (so || subject) + (so || item),
data = dat,
control = lmerControl(calc.derivs = FALSE)
)
## save t-value
tvals[i] <- summary(m)$coefficients[2, 3]
}
mean(abs(tvals) > 2)
```
If we also want to examine the distribution of the data generated, and the distribution of the parameters under repeated sampling, we can easily record that information within the for-loop:
```{r cache=TRUE,warning=FALSE,message=FALSE}
n <- dim(dat)[1]
nsim <- 100
ysims <- matrix(rep(NA, n * nsim), ncol = nsim)
for (i in 1:100) {
## generate data:
ysim <- simLMM(
formula = ~ 1 + so + (1 + so | subject) + (1 + so | item),
data = dat,
LMM = m_lmer,
CP = 0.0,
empirical = FALSE, verbose = FALSE,
family = "gaussian"
)
## store simulated data:
ysims[, i] <- ysim
## add current simulated data to data-frame:
dat$ysim <- ysim
## fit model to simulated data:
m <- lme4::lmer(ysim ~ so + (so || subject) + (so || item),
data = dat,
control = lmerControl(calc.derivs = FALSE)
)
## save t-value
tvals[i] <- summary(m)$coefficients[2, 3]
}
mean(abs(tvals) > 2)
```
```{r}
hist(gg05e1$rawRT,
freq = FALSE, ylab = "density",
xlim = c(-1000, 5000),
main = "", xlab = "reading times (ms)"
)
for (i in 1:100) {
lines(density(ysims[, i]))
}
```
As the above plot shows, a model using raw readings times lead to predicted reading times including negative values, which is obviously implausible.
If we want to fit the model on log RTs, the code changes as follows.
First, the model is fit to the data on the log ms scale:
```{r}
m_lmer <- lmer(logrt ~ so + (1 + so || subject) + (1 + so || item), gg05e1)
summary(m_lmer)
```
The design remains unchanged; only the for-loop changes: the `simLMM` function is passed through the `exp()` function, to exponentiate the data generated on the log scale.
```{r cache=TRUE,warning=FALSE,message=FALSE}
tvals <- rep(NA, 100)
for (i in 1:100) {
## generate data:
dat$ysim <- exp(simLMM(
formula = ~ 1 + so + (1 + so | subject) + (1 + so | item),
data = dat,
LMM = m_lmer,
CP = 0.0,
empirical = FALSE, verbose = FALSE,
family = "gaussian"
))
## fit model to simulated data:
m <- lme4::lmer(log(ysim) ~ so + (so || subject) + (so || item),
data = dat,
control = lmerControl(calc.derivs = FALSE)
)
## save t-value
tvals[i] <- summary(m)$coefficients[2, 3]
}
mean(abs(tvals) > 2)
```
The model fit on log RTs produces much more realistic data:
```{r cache=TRUE,warning=FALSE,message=FALSE}
n <- dim(dat)[1]
nsim <- 100
ysims <- matrix(rep(NA, n * nsim), ncol = nsim)
for (i in 1:100) {
## generate data:
ysim <- exp(simLMM(
formula = ~ 1 + so + (1 + so | subject) +
(1 + so | item),
data = dat,
LMM = m_lmer,
CP = 0.0,
empirical = FALSE, verbose = FALSE,
family = "gaussian"
))
## store simulated data:
ysims[, i] <- ysim
## add current simulated data to data-frame:
dat$ysim <- ysim
## fit model to simulated data:
m <- lme4::lmer(log(ysim) ~ so + (so || subject) + (so || item),
data = dat,
control = lmerControl(calc.derivs = FALSE)
)
## save t-value
tvals[i] <- summary(m)$coefficients[2, 3]
}
mean(abs(tvals) > 2)
```
```{r}
hist(gg05e1$rawRT,
freq = FALSE, ylab = "density",
xlim = c(-1000, 5000),
main = "", xlab = "reading times (ms)", ylim = c(0, 0.003)
)
for (i in 1:100) {
lines(density(ysims[, i]))
}
```
### Simulating data in factorial designs
The `designr` library can be used to generate data from typical factorial designs used in psychology and linguistics. For example, suppose we have a $2\times 2$ design
```{r}
design <- fixed.factor("distance", c("long", "short")) +
fixed.factor("predictability", c("high", "low")) +
random.factor("Subject", instances = 4) + ## 4x4 = 16 subjects
random.factor("Item", instances = 4) + ## 4x4=16 items
random.factor(c("Subject", "Item"), groups = c("distance", "predictability"))
simdat <- design.codes(design)
```
## Exercises {#sec:Simulationexercises}
```{exercise,SimulationexercisesPart1}
Drawing a power curve given a range of effect sizes
```
Use the simulation code as provided to compute a power function for effects sizes for the English relative clause effect ranging from 0.025, 0.05, 0.10, and 0.15, given that you have 16 items and 42 participants.
```{exercise,SimulationexercisesPart2}
Power and log-transformation
```
Modify the simulation code to generate not log-normally distributed data, but normally distributed data. Refit the @grodner data using raw reading times (i.e., do not log-transform them), and then use the parameter estimates from the data to compute a power function for effects sizes for the relative clause effect ranging from 10, 30, 60, 80 ms, given that you have 16 items and 42 participants. Compare your power curve with that of Part 1.
```{exercise,SimulationexercisesPart3}
Evaluating models by generating simulated data
```
Generate data from the simulation function assuming a log-normal likelihood and then generate data from the function you wrote in Part 2 that assumes a normal likelihood. Compare the distributions of the two sets of simulated data to the observed distributions. Which simulation code produces more realistic data, and why?
```{exercise,SimulationexercisesPart4}
Using simulation to check parameter recovery
```
Check whether the simulation code you wrote assuming a normal likelihood can recover the parameters.
```{exercise,SimulationexercisesPart5}
Sample size calculations using simulation
```
Load the data-set shown below:
```{r}
data("df_gibsonwu")
```
Use simulation to determine how many subjects you would need to achieve power of 80%, given 16 items, and an effect size of 0.02 on the log ms scale. Draw a power curve: on the x-axis show the number of subjects, and on the y-axis the estimated power. Now draw two further curves, one for an effect size of 0.05 and another for an effect size of 0.10. This gives you a power curve, taking the uncertainty in the effect size into account.