library(lme4)
#> Loading required package: Matrix
library(rstanarm)
#> Loading required package: Rcpp
#> rstanarm (Version 2.17.4, packaged: 2018-04-13 01:51:52 UTC)
#> - Do not expect the default priors to remain the same in future rstanarm versions.
#> Thus, R scripts should specify priors explicitly, even if they are just the defaults.
#> - For execution on a local, multicore CPU with excess RAM we recommend calling
#> options(mc.cores = parallel::detectCores())
#> - Plotting theme set to bayesplot::theme_default().
library(tidyverse)
#> -- Attaching packages ------------------------------------------------------------------ tidyverse 1.2.1 --
#> v ggplot2 3.0.0 v purrr 0.2.5
#> v tibble 1.4.2 v dplyr 0.7.6
#> v tidyr 0.8.1 v stringr 1.3.1
#> v readr 1.1.1 v forcats 0.3.0
#> -- Conflicts --------------------------------------------------------------------- tidyverse_conflicts() --
#> x tidyr::expand() masks Matrix::expand()
#> x dplyr::filter() masks stats::filter()
#> x dplyr::lag() masks stats::lag()
theme_set(theme_grey())
sleepstudy <- sleepstudy %>%
as_tibble() %>%
mutate(Subject = as.character(Subject))
b <- stan_glmer(
Reaction ~ Days + (Days | Subject),
family = gaussian(),
data = sleepstudy,
prior = normal(0, 2),
prior_intercept = normal(0, 5),
prior_covariance = decov(regularization = 2),
prior_aux = cauchy(0, 1),
chains = 1)
#>
#> SAMPLING FOR MODEL 'continuous' NOW (CHAIN 1).
#>
#> Gradient evaluation took 0 seconds
#> 1000 transitions using 10 leapfrog steps per transition would take 0 seconds.
#> Adjust your expectations accordingly!
#>
#>
#> Iteration: 1 / 2000 [ 0%] (Warmup)
#> Iteration: 200 / 2000 [ 10%] (Warmup)
#> Iteration: 400 / 2000 [ 20%] (Warmup)
#> Iteration: 600 / 2000 [ 30%] (Warmup)
#> Iteration: 800 / 2000 [ 40%] (Warmup)
#> Iteration: 1000 / 2000 [ 50%] (Warmup)
#> Iteration: 1001 / 2000 [ 50%] (Sampling)
#> Iteration: 1200 / 2000 [ 60%] (Sampling)
#> Iteration: 1400 / 2000 [ 70%] (Sampling)
#> Iteration: 1600 / 2000 [ 80%] (Sampling)
#> Iteration: 1800 / 2000 [ 90%] (Sampling)
#> Iteration: 2000 / 2000 [100%] (Sampling)
#>
#> Elapsed Time: 4.778 seconds (Warm-up)
#> 2.5 seconds (Sampling)
#> 7.278 seconds (Total)
library(tidybayes)
#> NOTE: As of tidybayes version 1.0, several functions, arguments, and output column names
#> have undergone significant name changes in order to adopt a unified naming scheme.
#> See help('tidybayes-deprecated') for more information.
# Create a `newdata` argument for prediction functions
prediction_grid <- sleepstudy %>%
expand(crossing(Subject = c(Subject, "NEW SUBJECT"), Days))
# Get 20 samples per newdata row
predictions <- prediction_grid %>%
tidybayes::add_fitted_draws(model = b, n = 20)
ggplot(sleepstudy) +
aes(x = Days, y = Reaction) +
geom_line(
aes(y = .value, group = .draw),
data = predictions,
alpha = .2) +
geom_point() +
facet_wrap("Subject")
