<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/diffusion-wiener-model-analysis-with-brms-part-ii-model-diagnostics-and-model-fit/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://singmann.org/wiener-model-analysis-with-brms-part-ii/"> Computational Psychology - Henrik Singmann</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>This is the considerably belated second part of my blog series on fitting diffusion models (or better, the 4-parameter Wiener model) with <a rel="nofollow" href="https://cran.r-project.org/package=brms" target="_blank"><code>brms</code></a>. <a rel="nofollow" href="http://singmann.org/wiener-model-analysis-with-brms-part-i/" target="_blank">The first part</a> discusses how to set up the data and model. This second part is concerned with perhaps the most important steps in each model based data analysis, model diagnostics and the assessment of model fit. Note, the code in the part is completely self sufficient and can be run without running the code of part I.</p>
<h3>Setup</h3>
<p>At first, we load quite a few packages that we will need down the way. Obviously <code>brms</code>, but also some of the packages from the <a rel="nofollow" href="https://www.tidyverse.org/" target="_blank"><code>tidyverse</code></a> (i.e., <code>dplyr</code>, <code>tidyr</code>, <code>tibble</code>, and <code>ggplot2</code>). It took me a little time to jump on the <code>tidyverse</code> bandwagon, but now that I use it more and more I cannot deny its utility. If your data can be made ‘tidy’, the coherent set of tools offered by the <code>tidyverse</code> make many seemingly complicated tasks pretty easy. A few examples of this will be shown below. If you need more introduction, I highly recommend the awesome <a rel="nofollow" href="http://r4ds.had.co.nz/" target="_blank">‘R for Data Science’ book by Grolemund and Wickham</a>, which they made available for free! We also need <code>gridExtra</code> for combining plots and <code>DescTools</code> for the concordance correlation coefficient CCC used below.</p>
<pre data-enlighter-language="null">library(&quot;brms&quot;)
library(&quot;dplyr&quot;)
library(&quot;tidyr&quot;)
library(&quot;tibble&quot;)    # for rownames_to_column
library(&quot;ggplot2&quot;)
library(&quot;gridExtra&quot;) # for grid.arrange
library(&quot;DescTools&quot;) # for CCC</pre>
<p>As in part I, we need package <code>rtdists</code> for the data.</p>
<pre data-enlighter-language="null">data(speed_acc, package = &quot;rtdists&quot;)
speed_acc &lt;- droplevels(speed_acc[!speed_acc$censor,]) # remove extreme RTs
speed_acc &lt;- droplevels(speed_acc[ speed_acc$frequency %in% 
                                     c(&quot;high&quot;, &quot;nw_high&quot;),])
speed_acc$response2 &lt;- as.numeric(speed_acc$response)-1</pre>
<p>I have uploaded the binary R data file containing the fitted model object as well as the generated posterior predictive distributions to github, from which we can download them directly into <code>R</code>. Note that I needed to go the way via a temporary folder. If there is a way without that I would be happy to learn about it.</p>
<pre data-enlighter-language="null">tmp &lt;- tempdir()
download.file(&quot;https://singmann.github.io/files/brms_wiener_example_fit.rda&quot;, 
              file.path(tmp, &quot;brms_wiener_example_fit.rda&quot;))
download.file(&quot;https://singmann.github.io/files/brms_wiener_example_predictions.rda&quot;, 
              file.path(tmp, &quot;brms_wiener_example_predictions.rda&quot;))
load(file.path(tmp, &quot;brms_wiener_example_fit.rda&quot;))
load(file.path(tmp, &quot;brms_wiener_example_predictions.rda&quot;))</pre>
<h3>Model Diagnostics</h3>
<p>We already know from <a rel="nofollow" href="http://singmann.org/wiener-model-analysis-with-brms-part-i/" target="_blank">part I</a> that there are a few divergent transitions. If this were a real analysis we therefore would not be satisfied with the current fit and try to rerun <code>brm</code> with an increased <code>adapt_delta</code> with the hope that this removes the divergent transitions. The <a rel="nofollow" href="http://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmup" target="_blank">Stan warning guidelines</a> clearly state that “the validity of the estimates is not guaranteed if there are post-warmup divergences”. However, it is unclear what the actual impact of the small number of divergent transitions (&lt; 10) observed here is on the posterior. Also, it is unclear what one can do if <code>adapt_delta</code> cannot be increased anymore and the model also cannot be reparameterized. Should all fits with any divergent transitions be completely disregarded? I hope the Stan team provides more guidelines to such questions in the future.</p>
<p>Coming back to our fit, as a first step in our model diagnostics we check the R-hat statistic as well as the number of effective samples. Specifically, we look at the parameters with the highest R² and lowest number of effective samples.</p>
<pre data-enlighter-language="null">tail(sort(rstan::summary(fit_wiener$fit)$summary[,&quot;Rhat&quot;]))
#                      sd_id__conditionaccuracy:frequencyhigh 
#                                                        1.00 
#                              r_id__bs[15,conditionaccuracy] 
#                                                        1.00 
#                                    b_bias_conditionaccuracy 
#                                                        1.00 
# cor_id__conditionspeed:frequencyhigh__ndt_conditionaccuracy 
#                                                        1.00 
#                                   sd_id__ndt_conditionspeed 
#                                                        1.00 
#  cor_id__conditionspeed:frequencynw_high__bs_conditionspeed 
#                                                        1.01 
head(sort(rstan::summary(fit_wiener$fit)$summary[,&quot;n_eff&quot;]))
#                                     lp__ 
#                                      462 
#        b_conditionaccuracy:frequencyhigh 
#                                      588 
#                sd_id__ndt_conditionspeed 
#                                      601 
#      sd_id__conditionspeed:frequencyhigh 
#                                      646 
#           b_conditionspeed:frequencyhigh 
#                                      695 
# r_id[12,conditionaccuracy:frequencyhigh] 
#                                      712</pre>
<p>Both are unproblematic (i.e., <code>R-hat</code> &lt; 1.05 and <code>n_eff</code> > 100) and suggest that the sampler has converged on the stationary distribution. If anyone has a similar oneliner to return the number of divergent transitions, I would be happy to learn about it.</p>
<p>We also visually inspect the chain behavior of a few semi-randomly selected parameters.</p>
<pre data-enlighter-language="null">pars &lt;- parnames(fit_wiener)
pars_sel &lt;- c(sample(pars[1:10], 3), sample(pars[-(1:10)], 3))
plot(fit_wiener, pars = pars_sel, N = 6, 
     ask = FALSE, exact_match = TRUE, newpage = TRUE, plot = TRUE)</pre>
<p><img data-orig-file="https://i1.wp.com/singmann.org/wp-content/uploads/2018/01/chains.png?fit=576%2C768" data-orig-size="576,768" data-medium-file="https://i1.wp.com/singmann.org/wp-content/uploads/2018/01/chains.png?fit=225%2C300" data-attachment-id="628" data-image-meta="{" data-image-description="" src="https://i1.wp.com/singmann.org/wp-content/uploads/2018/01/chains.png?resize=576%2C768" data-permalink="http://singmann.org/wiener-model-analysis-with-brms-part-ii/chains/" data-large-file="https://i1.wp.com/singmann.org/wp-content/uploads/2018/01/chains.png?fit=576%2C768" alt="" data-image-title="chains" sizes="(max-width: 576px) 100vw, 576px" width="450" data-comments-opened="1" class="wp-image-628" data-recalc-dims="1"></p>
<p>This visual inspection confirms the earlier conclusion. For all parameters the posteriors look well-behaved and the chains appears to mix well.</p>
<p>Finally, in the literature there are some discussions about parameter trade-offs for the diffusion and related models. These trade-offs supposedly make fitting the diffusion model in a Bayesian setting particularly complicated. To investigate whether fitting the Wiener model with HMC as implemented in <code>Stan</code> (i.e., NUTS) also shows this pattern we take a look at the joint posterior of the fixed-effects of the main Wiener parameters for the accuracy condition. For this we use the <code>stanfit</code> method of the <code>pairs</code> function and set the <code>condition</code> to <code>&quot;divergent__&quot;</code>. This plots the few divergent transitions above the diagonal and the remaining samples below the diagonal.</p>
<pre data-enlighter-language="null">pairs(fit_wiener$fit, pars = pars[c(1, 3, 5, 7, 9)], condition = &quot;divergent__&quot;)</pre>
<p><img data-orig-file="https://i1.wp.com/singmann.org/wp-content/uploads/2018/01/pairsn.png?fit=619%2C619" data-orig-size="619,619" data-medium-file="https://i1.wp.com/singmann.org/wp-content/uploads/2018/01/pairsn.png?fit=300%2C300" data-attachment-id="649" data-image-meta="{" data-image-description="" src="https://i1.wp.com/singmann.org/wp-content/uploads/2018/01/pairsn.png?resize=619%2C619" data-permalink="http://singmann.org/wiener-model-analysis-with-brms-part-ii/pairsn/" data-large-file="https://i1.wp.com/singmann.org/wp-content/uploads/2018/01/pairsn.png?fit=619%2C619" alt="" data-image-title="pairsn" sizes="(max-width: 619px) 100vw, 619px" width="450" data-comments-opened="1" class="wp-image-649" data-recalc-dims="1"></p>
<p>This plot shows some correlations, but nothing too dramatic. HMC appears to sample quite efficiently from the Wiener model.</p>
<p>Next we also take a look at the correlations across all parameters (not only the fixed effects).</p>
<pre data-enlighter-language="null">posterior &lt;- as.mcmc(fit_wiener, combine_chains = TRUE)
cor_posterior &lt;- cor(posterior)
cor_posterior[lower.tri(cor_posterior, diag = TRUE)] &lt;- NA
cor_long &lt;- as.data.frame(as.table(cor_posterior))
cor_long &lt;- na.omit(cor_long)
tail(cor_long[order(abs(cor_long$Freq)),], 10)
#                              Var1                         Var2   Freq
# 43432        b_ndt_conditionspeed  r_id__ndt[1,conditionspeed] -0.980
# 45972 r_id__ndt[4,conditionspeed] r_id__ndt[11,conditionspeed]  0.982
# 46972        b_ndt_conditionspeed r_id__ndt[16,conditionspeed] -0.982
# 44612        b_ndt_conditionspeed  r_id__ndt[6,conditionspeed] -0.983
# 46264        b_ndt_conditionspeed r_id__ndt[13,conditionspeed] -0.983
# 45320        b_ndt_conditionspeed  r_id__ndt[9,conditionspeed] -0.984
# 45556        b_ndt_conditionspeed r_id__ndt[10,conditionspeed] -0.985
# 46736        b_ndt_conditionspeed r_id__ndt[15,conditionspeed] -0.985
# 44140        b_ndt_conditionspeed  r_id__ndt[4,conditionspeed] -0.990
# 45792        b_ndt_conditionspeed r_id__ndt[11,conditionspeed] -0.991</pre>
<p>This table lists the ten largest absolute values of correlations among posteriors for all pairwise combinations of parameters. The value in column <code>Freq</code> somewhat unintuitively is the observed  correlation among the posteriors of the two parameters listed in the two previous columns. To create this table I used a <a rel="nofollow" href="https://stackoverflow.com/a/7074856/289572" target="_blank">trick from SO</a> using <code>as.table</code>, which is responsible for labeling the column containing the correlation value <code>Freq</code>.</p>
<p>What the table shows is some extreme correlations for the individual-level deviations (the first index in the squared brackets of the parameter names seems to be the participant number). Let us visualize these correlations as well.</p>
<pre data-enlighter-language="null">pairs(fit_wiener$fit, pars = 
        c(&quot;b_ndt_conditionspeed&quot;, 
          &quot;r_id__ndt[11,conditionspeed]&quot;,
          &quot;r_id__ndt[4,conditionspeed]&quot;), 
      condition = &quot;divergent__&quot;)</pre>
<p><img data-orig-file="https://i2.wp.com/singmann.org/wp-content/uploads/2018/01/pairs2.png?fit=384%2C384" data-orig-size="384,384" data-medium-file="https://i2.wp.com/singmann.org/wp-content/uploads/2018/01/pairs2.png?fit=300%2C300" data-attachment-id="632" data-image-meta="{" data-image-description="" src="https://i2.wp.com/singmann.org/wp-content/uploads/2018/01/pairs2.png?resize=384%2C384" data-permalink="http://singmann.org/wiener-model-analysis-with-brms-part-ii/pairs2/" data-large-file="https://i2.wp.com/singmann.org/wp-content/uploads/2018/01/pairs2.png?fit=384%2C384" alt="" data-image-title="pairs2" sizes="(max-width: 384px) 100vw, 384px" width="384" data-comments-opened="1" class="wp-image-632" data-recalc-dims="1" height="384"></p>
<p>This plot shows that some of the individual-level parameters are not well estimated.</p>
<p>However, overall these extreme correlations appear rather rarely.</p>
<pre data-enlighter-language="null">hist(cor_long$Freq, breaks = 40)</pre>
<p><img data-orig-file="https://i1.wp.com/singmann.org/wp-content/uploads/2018/01/hist_corr.png?fit=480%2C288" data-orig-size="480,288" data-medium-file="https://i1.wp.com/singmann.org/wp-content/uploads/2018/01/hist_corr.png?fit=300%2C180" data-attachment-id="633" data-image-meta="{" data-image-description="" src="https://i1.wp.com/singmann.org/wp-content/uploads/2018/01/hist_corr.png?resize=480%2C288" data-permalink="http://singmann.org/wiener-model-analysis-with-brms-part-ii/hist_corr/" data-large-file="https://i1.wp.com/singmann.org/wp-content/uploads/2018/01/hist_corr.png?fit=480%2C288" alt="" data-image-title="hist_corr" sizes="(max-width: 480px) 100vw, 480px" width="450" data-comments-opened="1" class="wp-image-633" data-recalc-dims="1"></p>
<p>Overall the model diagnostics do not show any particularly worrying behavior (with the exception of the divergent transitions). We have learned that a few of the individual-level estimates for some of the parameters are not very trustworthy. However, this does not disqualify the overall fit. The main take away from this fact is that we would need to be careful in interpreting the individual-level estimates. Thus, we assume the fit is okay and continue with the next step of the analysis.</p>
<h3>Assessing Model Fit</h3>
<p>We will now investigate the model fit. That is, we will investigate whether the model provides an adequate description of the observed data. We will mostly do so via graphical checks. To do so, we need to prepare the posterior predictive distribution and the data. As a first step, we combine the posterior predictive distributions with the data.</p>
<pre data-enlighter-language="null">d_speed_acc &lt;- as_tibble(cbind(speed_acc, as_tibble(t(pred_wiener))))</pre>
<p>Then we calculate three important measures (or test statistics <em>T()</em>) on the individual level for each cell of the design (i.e., combination of <code>condition</code> and <code>frequency</code> factors):</p>
<ul>
<li>Probability of giving an upper boundary response (i.e., respond “nonword”).</li>
<li>Median RTs for responses to the upper boundary.</li>
<li>Median RTs for the lower boundary.</li>
</ul>
<p>We first calculate this for each sample of the posterior predictive distribution. We then summarize these three measures by calculating the median and some additional quantiles across the posterior predictive distribution. We calculate all of this in one step using a somewhat long combination of <code>dplyr</code> and <code>tidyr</code> magic.</p>
<pre data-enlighter-language="null">d_speed_acc_agg &lt;- d_speed_acc %>% 
  group_by(id, condition, frequency) %>%  # select grouping vars
  summarise_at(.vars = vars(starts_with(&quot;V&quot;)), 
               funs(prob.upper = mean(. > 0),
                    medrt.lower = median(abs(.[. &lt; 0]) ),
                    medrt.upper = median(.[. > 0] )
               )) %>% 
  ungroup %>% 
  gather(&quot;key&quot;, &quot;value&quot;, -id, -condition, -frequency) %>% # remove grouping vars
  separate(&quot;key&quot;, c(&quot;rep&quot;, &quot;measure&quot;), sep = &quot;_&quot;) %>% 
  spread(measure, value) %>% 
  group_by(id, condition, frequency) %>% # select grouping vars
  summarise_at(.vars = vars(prob.upper, medrt.lower, medrt.upper), 
               .funs = funs(median = median(., na.rm = TRUE),
                            llll = quantile(., probs = 0.01,na.rm = TRUE),
                            lll = quantile(., probs = 0.025,na.rm = TRUE),
                            ll = quantile(., probs = 0.1,na.rm = TRUE),
                            l = quantile(., probs = 0.25,na.rm = TRUE),
                            h = quantile(., probs = 0.75,na.rm = TRUE),
                            hh = quantile(., probs = 0.9,na.rm = TRUE),
                            hhh = quantile(., probs = 0.975,na.rm = TRUE),
                            hhhh = quantile(., probs = 0.99,na.rm = TRUE)
               ))</pre>
<p>Next, we calculate the three measures also for the data and combine it with the results from the posterior predictive distribution in one <code>data.frame</code> using <code>left_join</code>.</p>
<pre data-enlighter-language="null">speed_acc_agg &lt;- speed_acc %>% 
  group_by(id, condition, frequency) %>% # select grouping vars
  summarise(prob.upper = mean(response == &quot;nonword&quot;),
            medrt.upper = median(rt[response == &quot;nonword&quot;]),
            medrt.lower = median(rt[response == &quot;word&quot;])
  ) %>% 
  ungroup %>% 
  left_join(d_speed_acc_agg)</pre>
<h4>Aggregated Model-Fit</h4>
<p>The first important question is whether our model can adequately describe the overall patterns in the data aggregated across participants. For this we simply aggregate the results obtained in the previous step (i.e., the summary results from the posterior predictive distribution as well as the test statistics from the data) using <code>mean</code>.</p>
<pre data-enlighter-language="null">d_speed_acc_agg2 &lt;- speed_acc_agg %>% 
  group_by(condition, frequency) %>% 
  summarise_if(is.numeric, mean, na.rm = TRUE) %>% 
  ungroup</pre>
<p>We then use these summaries and plot predictions (in grey and black) as well as data (in red) for the three measures. The inner (fat) error bars show the 80% credibility intervals (CIs), the outer (thin) error bars show the 95% CIs. The black circle shows the median of the posterior predictive distributions.</p>
<pre data-enlighter-language="null">new_x &lt;- with(d_speed_acc_agg2, 
              paste(rep(levels(condition), each = 2), 
                    levels(frequency), sep = &quot;\n&quot;))

p1 &lt;- ggplot(d_speed_acc_agg2, aes(x = condition:frequency)) +
  geom_linerange(aes(ymin =  prob.upper_lll, ymax =  prob.upper_hhh), 
                 col = &quot;darkgrey&quot;) + 
  geom_linerange(aes(ymin =  prob.upper_ll, ymax =  prob.upper_hh), 
                 size = 2, col = &quot;grey&quot;) + 
  geom_point(aes(y = prob.upper_median), shape = 1) +
  geom_point(aes(y = prob.upper), shape = 4, col = &quot;red&quot;) +
  ggtitle(&quot;Response Probabilities&quot;) + 
  ylab(&quot;Probability of upper resonse&quot;) + xlab(&quot;&quot;) +
  scale_x_discrete(labels = new_x)

p2 &lt;- ggplot(d_speed_acc_agg2, aes(x = condition:frequency)) +
  geom_linerange(aes(ymin =  medrt.upper_lll, ymax =  medrt.upper_hhh), 
                 col = &quot;darkgrey&quot;) + 
  geom_linerange(aes(ymin =  medrt.upper_ll, ymax =  medrt.upper_hh), 
                 size = 2, col = &quot;grey&quot;) + 
  geom_point(aes(y = medrt.upper_median), shape = 1) +
  geom_point(aes(y = medrt.upper), shape = 4, col = &quot;red&quot;) +
  ggtitle(&quot;Median RTs upper&quot;) + 
  ylab(&quot;RT (s)&quot;) + xlab(&quot;&quot;) +
  scale_x_discrete(labels = new_x)

p3 &lt;- ggplot(d_speed_acc_agg2, aes(x = condition:frequency)) +
  geom_linerange(aes(ymin =  medrt.lower_lll, ymax =  medrt.lower_hhh), 
                 col = &quot;darkgrey&quot;) + 
  geom_linerange(aes(ymin =  medrt.lower_ll, ymax =  medrt.lower_hh), 
                 size = 2, col = &quot;grey&quot;) + 
  geom_point(aes(y = medrt.lower_median), shape = 1) +
  geom_point(aes(y = medrt.lower), shape = 4, col = &quot;red&quot;) +
  ggtitle(&quot;Median RTs lower&quot;) + 
  ylab(&quot;RT (s)&quot;) + xlab(&quot;&quot;) +
  scale_x_discrete(labels = new_x)

grid.arrange(p1, p2, p3, ncol = 2)</pre>
<p> </p>
<p><img data-orig-file="https://i1.wp.com/singmann.org/wp-content/uploads/2018/01/pp1d.png?fit=576%2C576" data-orig-size="576,576" data-medium-file="https://i1.wp.com/singmann.org/wp-content/uploads/2018/01/pp1d.png?fit=300%2C300" data-attachment-id="646" data-image-meta="{" data-image-description="" src="https://i1.wp.com/singmann.org/wp-content/uploads/2018/01/pp1d.png?resize=576%2C576" data-permalink="http://singmann.org/wiener-model-analysis-with-brms-part-ii/pp1d/" data-large-file="https://i1.wp.com/singmann.org/wp-content/uploads/2018/01/pp1d.png?fit=576%2C576" alt="" data-image-title="pp1d" sizes="(max-width: 576px) 100vw, 576px" width="450" data-comments-opened="1" class="wp-image-646" data-recalc-dims="1"></p>
<p>Inspection of the plots show no dramatic misfit. Overall the model appears to be able to describe the general patterns in the data. Only the response probabilities for words (i.e., <code>frequency</code> = <code>high</code>) appears to be estimated too low. The red <code>x</code> appear to be outside the 80% CIs but possibly also outside the 95% CIs.</p>
<p>The plots of the RTs show an interesting (but not surprising) pattern. The posterior predictive distributions for the rare responses (i.e., “word” responses for upper/non-word stimuli and “nonword” response to lower/word stimuli) are relatively wide. In contrast, the posterior predictive distributions for the common responses are relatively narrow. In each case, the observed median is inside the 80% CI and also quite near to the predicted median.</p>
<h4>Individual-Level Fit</h4>
<p>To investigate the pattern of predicted response probabilities further, we take a look at them on the individual level. We again plot the response probabilities in the same way as above, but separated by participant <code>id</code>.</p>
<pre data-enlighter-language="null">ggplot(speed_acc_agg, aes(x = condition:frequency)) +
  geom_linerange(aes(ymin =  prob.upper_lll, ymax =  prob.upper_hhh), 
                 col = &quot;darkgrey&quot;) + 
  geom_linerange(aes(ymin =  prob.upper_ll, ymax =  prob.upper_hh), 
                 size = 2, col = &quot;grey&quot;) + 
  geom_point(aes(y = prob.upper_median), shape = 1) +
  geom_point(aes(y = prob.upper), shape = 4, col = &quot;red&quot;) +
  facet_wrap(~id, ncol = 3) +
  ggtitle(&quot;Prediced (in grey) and observed (red) response probabilities by ID&quot;) + 
  ylab(&quot;Probability of upper resonse&quot;) + xlab(&quot;&quot;) +
  scale_x_discrete(labels = new_x)</pre>
<p><img data-orig-file="https://i0.wp.com/singmann.org/wp-content/uploads/2018/01/pp_i.png?fit=619%2C1152" data-orig-size="619,1152" data-medium-file="https://i0.wp.com/singmann.org/wp-content/uploads/2018/01/pp_i.png?fit=161%2C300" data-attachment-id="650" data-image-meta="{" data-image-description="" src="https://i0.wp.com/singmann.org/wp-content/uploads/2018/01/pp_i.png?resize=619%2C1152" data-permalink="http://singmann.org/wiener-model-analysis-with-brms-part-ii/pp_i/" data-large-file="https://i0.wp.com/singmann.org/wp-content/uploads/2018/01/pp_i.png?fit=550%2C1024" alt="" data-image-title="pp_i" sizes="(max-width: 619px) 100vw, 619px" width="450" data-comments-opened="1" class="wp-image-650" data-recalc-dims="1"></p>
<p>This plot shows a similar pattern as the aggregated data. For none of the participants do we observe dramatic misfit. Furthermore, response probabilities to non-word stimuli appear to be predicted rather well. In contrast, response probabilities for word-stimuli are overall predicted to be lower than observed. However, this misfit does not seem to be too strong.</p>
<p>As a next step we look at the coverage probabilities of our three measures across individuals. That is, we calculate for each of the measures, for each of the cells of the design, and for each of the CIs (i.e., 50%, 80%, 95%, and 99%), the proportion of participants for which the observed test statistics falls into the corresponding CI.</p>
<pre data-enlighter-language="null">speed_acc_agg %>% 
  mutate(prob.upper_99 = (prob.upper >= prob.upper_llll) &amp; 
           (prob.upper &lt;= prob.upper_hhhh),
         prob.upper_95 = (prob.upper >= prob.upper_lll) &amp; 
           (prob.upper &lt;= prob.upper_hhh),
         prob.upper_80 = (prob.upper >= prob.upper_ll) &amp; 
           (prob.upper &lt;= prob.upper_hh),
         prob.upper_50 = (prob.upper >= prob.upper_l) &amp; 
           (prob.upper &lt;= prob.upper_h),
         medrt.upper_99 = (medrt.upper > medrt.upper_llll) &amp; 
           (medrt.upper &lt; medrt.upper_hhhh),
         medrt.upper_95 = (medrt.upper > medrt.upper_lll) &amp; 
           (medrt.upper &lt; medrt.upper_hhh),
         medrt.upper_80 = (medrt.upper > medrt.upper_ll) &amp; 
           (medrt.upper &lt; medrt.upper_hh),
         medrt.upper_50 = (medrt.upper > medrt.upper_l) &amp; 
           (medrt.upper &lt; medrt.upper_h),
         medrt.lower_99 = (medrt.lower > medrt.lower_llll) &amp; 
           (medrt.lower &lt; medrt.lower_hhhh),
         medrt.lower_95 = (medrt.lower > medrt.lower_lll) &amp; 
           (medrt.lower &lt; medrt.lower_hhh),
         medrt.lower_80 = (medrt.lower > medrt.lower_ll) &amp; 
           (medrt.lower &lt; medrt.lower_hh),
         medrt.lower_50 = (medrt.lower > medrt.lower_l) &amp; 
           (medrt.lower &lt; medrt.lower_h)
  ) %>% 
  group_by(condition, frequency) %>% ## grouping factors without id
  summarise_at(vars(matches(&quot;\\d&quot;)), mean, na.rm = TRUE) %>% 
  gather(&quot;key&quot;, &quot;mean&quot;, -condition, -frequency) %>% 
  separate(&quot;key&quot;, c(&quot;measure&quot;, &quot;ci&quot;), &quot;_&quot;) %>% 
  spread(ci, mean) %>% 
  as.data.frame()
#    condition frequency     measure    50     80    95    99
# 1   accuracy      high medrt.lower 0.706 0.8824 0.882 1.000
# 2   accuracy      high medrt.upper 0.500 0.8333 1.000 1.000
# 3   accuracy      high  prob.upper 0.529 0.7059 0.765 0.882
# 4   accuracy   nw_high medrt.lower 0.500 0.8125 0.938 0.938
# 5   accuracy   nw_high medrt.upper 0.529 0.8235 1.000 1.000
# 6   accuracy   nw_high  prob.upper 0.529 0.8235 0.941 0.941
# 7      speed      high medrt.lower 0.471 0.8824 0.941 1.000
# 8      speed      high medrt.upper 0.706 0.9412 1.000 1.000
# 9      speed      high  prob.upper 0.000 0.0588 0.588 0.647
# 10     speed   nw_high medrt.lower 0.706 0.8824 0.941 0.941
# 11     speed   nw_high medrt.upper 0.471 0.7647 1.000 1.000
# 12     speed   nw_high  prob.upper 0.235 0.6471 0.941 1.000</pre>
<p>As can be seen, for the RTs, the coverage probability is generally in line with the width of the CIs or even above it. Furthermore, for the common response (i.e., <code>upper</code> for <code>frequency</code> = <code>nw_high</code> and <code>lower</code> for <code>frequency</code> = <code>high</code>), the coverage probability is 1 for the 99% CIs in all cases.</p>
<p>Unfortunately, for the response probabilities, the coverage is not that great. especially in the <code>speed</code> condition and for tighter CIs. However, for the wide CIs the coverage probabilities is at least acceptable. Overall the results so far suggest that the model provides an adequate account. There are some misfits that should be kept in mind if one is interested in extending the model or fitting it to new data, but overall it provides a satisfactory account.</p>
<h4>QQ-plots: RTs</h4>
<p>The final approach for assessing the fit of the model will be based on more quantiles of the RT distribution (i.e., so far we only looked at th .5 quantile, the median). We will then plot individual observed versus predicted (i.e., mean from posterior predictive distribution) quantiles across conditions. For this we first calculate the quantiles per sample from the posterior predictive distribution and then aggregate across the samples. This is achieved via <code>dplyr::summarise_at</code> using a <code>list</code> column and <code>tidyr::unnest</code> to unstack the columns (see section 25.3 in <a rel="nofollow" href="http://r4ds.had.co.nz/" target="_blank">“R for data Science”</a>). We then combine the aggregated predicted RT quantiles with the observed RT quantiles.</p>
<pre data-enlighter-language="null">quantiles &lt;- c(0.1, 0.25, 0.5, 0.75, 0.9)

pp2 &lt;- d_speed_acc %>% 
  group_by(id, condition, frequency) %>%  # select grouping vars
  summarise_at(.vars = vars(starts_with(&quot;V&quot;)), 
               funs(lower = list(rownames_to_column(
                 data.frame(q = quantile(abs(.[. &lt; 0]), probs = quantiles)))),
                    upper = list(rownames_to_column(
                      data.frame(q = quantile(.[. > 0], probs = quantiles ))))
               )) %>% 
  ungroup %>% 
  gather(&quot;key&quot;, &quot;value&quot;, -id, -condition, -frequency) %>% # remove grouping vars
  separate(&quot;key&quot;, c(&quot;rep&quot;, &quot;boundary&quot;), sep = &quot;_&quot;) %>% 
  unnest(value) %>% 
  group_by(id, condition, frequency, boundary, rowname) %>% # grouping vars + new vars
  summarise(predicted = mean(q, na.rm = TRUE))

rt_pp &lt;- speed_acc %>% 
  group_by(id, condition, frequency) %>% # select grouping vars
  summarise(lower = list(rownames_to_column(
    data.frame(observed = quantile(rt[response == &quot;word&quot;], probs = quantiles)))),
    upper = list(rownames_to_column(
      data.frame(observed = quantile(rt[response == &quot;nonword&quot;], probs = quantiles ))))
  ) %>% 
  ungroup %>% 
  gather(&quot;boundary&quot;, &quot;value&quot;, -id, -condition, -frequency) %>%
  unnest(value) %>% 
  left_join(pp2)
</pre>
<p>To evaluate the agreement between observed and predicted quantiles we calculate for each cell and quantile the concordance correlation coefficient (CCC; e.g, <a rel="nofollow" href="http://dx.doi.org/10.1037/a0023351" target="_blank">Barchard, 2012, Psych. Methods</a>). The CCC is a measure of absolute agreement between two values and thus better suited than simple correlation. It is scaled from -1 to 1 where 1 represent perfect agreement, 0 no relationship, and -1 a correlation of -1 with same mean and variance of the two variables.</p>
<p>The following code produces QQ-plots for each condition and quantile separately for responses to the upper boundary and lower boundary. The value in the upper left of each plot gives the CCC measures of absolute agreement.</p>
<pre data-enlighter-language="null">plot_text &lt;- rt_pp %>% 
  group_by(condition, frequency, rowname, boundary) %>% 
  summarise(ccc = format(
    CCC(observed, predicted, na.rm = TRUE)$rho.c$est, 
    digits = 2))

p_upper &lt;- rt_pp %>% 
  filter(boundary == &quot;upper&quot;) %>% 
  ggplot(aes(x = observed, predicted)) +
  geom_abline(slope = 1, intercept = 0) +
  geom_point() +
  facet_grid(condition+frequency~ rowname) + 
  geom_text(data=plot_text[ plot_text$boundary == &quot;upper&quot;, ],
            aes(x = 0.5, y = 1.8, label=ccc), 
            parse = TRUE, inherit.aes=FALSE) +
  coord_fixed() +
  ggtitle(&quot;Upper responses&quot;) +
  theme_bw()

p_lower &lt;- rt_pp %>% 
  filter(boundary == &quot;lower&quot;) %>% 
  ggplot(aes(x = observed, predicted)) +
  geom_abline(slope = 1, intercept = 0) +
  geom_point() +
  facet_grid(condition+frequency~ rowname) + 
  geom_text(data=plot_text[ plot_text$boundary == &quot;lower&quot;, ],
            aes(x = 0.5, y = 1.6, label=ccc), 
            parse = TRUE, inherit.aes=FALSE) +
  coord_fixed() +
  ggtitle(&quot;Lower responses&quot;) +
  theme_bw()

grid.arrange(p_upper, p_lower, ncol = 1)</pre>
<p><img data-orig-file="https://i1.wp.com/singmann.org/wp-content/uploads/2018/01/qq_plots_wiener.png?fit=619%2C1152" data-orig-size="619,1152" data-medium-file="https://i1.wp.com/singmann.org/wp-content/uploads/2018/01/qq_plots_wiener.png?fit=161%2C300" data-attachment-id="652" data-image-meta="{" data-image-description="" src="https://i1.wp.com/singmann.org/wp-content/uploads/2018/01/qq_plots_wiener.png?resize=619%2C1152" data-permalink="http://singmann.org/wiener-model-analysis-with-brms-part-ii/qq_plots_wiener/" data-large-file="https://i1.wp.com/singmann.org/wp-content/uploads/2018/01/qq_plots_wiener.png?fit=550%2C1024" alt="" data-image-title="qq_plots_wiener" sizes="(max-width: 619px) 100vw, 619px" width="450" data-comments-opened="1" class="wp-image-652" data-recalc-dims="1"></p>
<p>Results show that overall the fit is better for the accuracy than the speed conditions. Furthermore, fit is better for the common response (i.e., <code>nw_high</code> for upper and <code>high</code> for lower responses). This latter observation is again not too surprising.</p>
<p>When comparing the fit for the different quantiles it appears that at least the median (i.e., 50%) shows acceptable values for the common response. However, especially in the speed condition the account of the other quantiles is not great. Nevertheless, dramatic misfit is only observed for the rare responses.</p>
<p>One possibility for some of the low CCCs in the speed conditions may be the comparatively low variances in some of the cells. For example, for both speed conditions that are common (i.e., <code>speed</code> &amp; <code>nw_high</code> for upper responses and <code>speed</code> &amp; <code>high</code> for lower responses) the visual inspection of the plot suggests a acceptable account while at the same time some CCC value are low (i.e., &lt; .5). Only for the 90% quantile in the speed conditions (and somewhat less the 75% quantile) we see some systematic deviations. The model predicts lower RTs than observed.</p>
<p>Taken together, the model appear to provide an at least acceptable account. The only slightly worrying patterns are (a) that the model predicts a slightly better performance for the word stimuli than observed (i.e., lower predicted rate of non-word responses than observed for word-stimuli) and (b) that in the speed conditions the model predicts somewhat longer RTs for the 75% and 90% quantile than observed.</p>
<p>The next step will be to look at differences between parameters as a function of the speed-accuracy condition. However, this will be the topic of the third blog post. I am hopeful it will not take two months this time.</p>
<p> </p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://singmann.org/wiener-model-analysis-with-brms-part-ii/"> Computational Psychology - Henrik Singmann</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/teTThGaON0U" height="1"></a></div>