Take output from brms prediction and turn to tidy form

pivot_celldraws_longer(mod_draws, data_strat, yhat_name = "pred_n_yes")

Arguments

mod_draws

Output from posterior_*pred, which is of dimension Iter (in rows) by Cells (in columns)

data_strat

Covariates to append to. The number of rows should be the number of Cells

yhat_name

The name of the value for the predicted outcome.

Value

A tidy long dataset with Iter x Cells rows. Columns will include the columns of data_strat, the iteration and cell ID, and the predicted value for that cell at that iteration.

Examples

library(dplyr)
#> 
#> Attaching package: ‘dplyr’
#> The following objects are masked from ‘package:stats’:
#> 
#>     filter, lag
#> The following objects are masked from ‘package:base’:
#> 
#>     intersect, setdiff, setequal, union
library(brms)
#> Loading required package: Rcpp
#> Warning: package ‘Rcpp’ was built under R version 4.0.5
#> Loading 'brms' package (version 2.16.3). Useful instructions
#> can be found by typing help('brms'). A more detailed introduction
#> to the package is available through vignette('brms_overview').
#> 
#> Attaching package: ‘brms’
#> The following object is masked from ‘package:stats’:
#> 
#>     ar

pred_df <- rename(acs_GA, n_response = count) # match variables with model call
posterior_draws <- posterior_epred(object = fit_GA,  # stanfit
                                   newdata = pred_df)

# output is matrix, not tidy form
class(posterior_draws)
#> [1] "matrix" "array" 
dim(posterior_draws)
#> [1] 4000  980

# tidy out
out <- pivot_celldraws_longer(mod_draws = posterior_draws,
                              data_strat = pred_df,
                              yhat_name = "pred_n_yes")

dim(out)
#> [1] 3920000      11
select(out, cd, n_response, cell, iter, pred_n_yes)
#> # A tibble: 3,920,000 × 5
#>    cd    n_response  cell  iter pred_n_yes
#>    <chr>      <dbl> <int> <dbl>      <dbl>
#>  1 GA-01       1082     1     1       637.
#>  2 GA-01       1082     1     2       429.
#>  3 GA-01       1082     1     3       506.
#>  4 GA-01       1082     1     4       412.
#>  5 GA-01       1082     1     5       485.
#>  6 GA-01       1082     1     6       555.
#>  7 GA-01       1082     1     7       527.
#>  8 GA-01       1082     1     8       513.
#>  9 GA-01       1082     1     9       394.
#> 10 GA-01       1082     1    10       439.
#> # … with 3,919,990 more rows