Sample size estimation for multi-level model with simr

Author

Phil Chalmers

library(SimDesign)

#-------------------------------------------------------------------

Generate <- function(condition, fixed_objects = NULL){
    x <- 1:condition$N
    g <- letters[1:3]
    X <- expand.grid(x=x, g=g)
    b <- c(2, -0.1) # fixed intercept and slope
    V1 <- 0.5 # random intercept variance
    s <- 1 # residual standard deviation
    model <- makeLmer(y ~ x + (1|g), fixef=b, VarCorr=V1, sigma=s, data=X)
    model
}

Analyse <- function(condition, dat, fixed_objects = NULL) {
    # powerSim() is noisy; tell it to use its "indoor voice"
    ret <- quiet(powerSim(dat, nsim=1, progress=FALSE)$pval)
    ret
}

Summarise <- function(condition, results, fixed_objects = NULL) {
    ret <- EDR(results)
    ret
}

#-------------------------------------------------------------------


# N = sample size per group (3 groups used with equal size)
Design <- createDesign(N = NA)

# sample size to 95% power
res <- SimSolve(design=Design, b=.95, interval=c(10, 50),
                generate=Generate, parallel=TRUE, verbose=FALSE,
                analyse=Analyse, summarise=Summarise, packages='simr')
res
# A tibble: 1 × 1
       N
   <dbl>
1 17.645
summary(res)
$root
[1] 17.64466

$predCI.root
  CI_2.5  CI_97.5 
17.43650 17.84429 

$b
[1] 0.95

$predCI.b
[1] 0.9430934 0.9561075

$terminated_early
[1] TRUE

$time
[1] 01m 38.69s

$iterations
[1] 54

$total.replications
[1] 10110

$tab
          y  x reps
2 0.8823913 16 4600
3 0.9306306 17 1110
4 0.9593350 18 3910
plot(res)

plot(res, type = 'history')