|
library(tidyverse) |
|
library(lmerTest) |
|
|
|
# subject count |
|
COUNT = 5 |
|
|
|
set.seed(8675309) |
|
|
|
# generate a unique intercept per subject |
|
data = tibble( |
|
subject = paste0("S", 1:COUNT), |
|
intercept = rnorm(COUNT, 0, 2) |
|
) %>% |
|
# fully cross with all combinations of factors |
|
expand_grid( |
|
color = factor(c("red", "green", "blue"), levels=c("red", "green", "blue")), |
|
shape = c("circle", "triangle"), |
|
size = factor(c("small", "large"), levels=c("small", "large")), |
|
# repeat each condition |
|
rep = 1:50 |
|
) %>% |
|
# simulate noisy responses |
|
mutate(response = intercept + (color=="blue")/2 + (shape=="triangle") * (size=="large")*2 + rnorm(n())) |
|
|
|
# typically trials are in shuffled order grouped by subject |
|
data = data %>% |
|
split(.$subject) %>% |
|
map( ~sample_frac(.) ) %>% |
|
bind_rows() |
|
|
|
# output |
|
data %>% |
|
select(-intercept, -rep) %>% |
|
mutate(response = round(response, 3)) %>% |
|
write_csv("~/dummydata3_factor.csv") |
|
|
|
#raw data |
|
ggplot(data) + |
|
aes(x=size, y=response, color=color, group=paste(subject, shape, color)) + |
|
geom_point(size=2, alpha=0.5, aes(shape=shape)) + |
|
geom_smooth(se=FALSE, method="lm", aes(linetype=shape), alpha=0.5) + |
|
facet_grid(. ~ shape) + |
|
theme_classic(16) |
|
|
|
# scaled by subject |
|
data %>% |
|
mutate(.by = subject, response = scale(response)) %>% |
|
ggplot() + |
|
aes(x=size, y=response, color=color, group=paste(subject, shape, color)) + |
|
geom_smooth(se=FALSE, method="lm", aes(linetype=shape), alpha=0.5) + |
|
theme_classic(16) |
|
|
|
|
|
# model it |
|
model = lmer(response ~ color*size*shape + |
|
(1|subject) + |
|
(1|color:subject) + (1|shape:subject) + (1|size:subject) + |
|
(1|subject:shape:color) + (1|subject:shape:size) + (1|subject:color:size) + |
|
(1|subject:color:size:shape), data) |
|
# ANOVA with df calculated by Kenward-Roger |
|
anova(model, ddf = "Kenward-Roger") |