<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/rtdists-0-7-2-response-time-distributions-now-with-rcpp-and-faster/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://singmann.org/rtdists-0-7-2-response-time-distributions-now-with-rcpp-and-faster/"> R-bloggers – Henrik Singmann – Computational Psychology</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>It took us quite a while but we have finally released a new version of <a rel="nofollow" href="https://cran.r-project.org/package=rtdists" target="_blank"><code>rtdists</code> to CRAN</a> which provides a few significant improvements. As a reminder, <code>rtdists</code></p>
<blockquote><p>[p]rovides response time distributions (density/PDF, distribution function/CDF, quantile function, and random generation): (a) Ratcliff diffusion model <span rel="{ 'api_user_id': '881472', 'pages': '', 'items': '{QQ2QRTIF}', 'format': '(%a%, %d%, %p%)', 'brackets': '', 'etal': '', 'separator': '', 'and': '' }"></span> based on C code by Andreas and Jochen Voss and (b) linear ballistic accumulator (LBA) <span rel="{ 'api_user_id': '881472', 'pages': '', 'items': '{4MC596NZ}', 'format': '(%a%, %d%, %p%)', 'brackets': '', 'etal': '', 'separator': '', 'and': '' }"></span> with different distributions underlying the drift rate.</p>
</blockquote>
<p>The main reason it took us relatively long to push the new version was that we had a problem with the <code>C</code> code for the diffusion model that we needed to sort out first. Specifically, the CDF (i.e., <code>pdiffusion</code>) in versions prior to 0.5-2 did not produce correct results in many cases (one consequence of this is that the model predictions given in the <a rel="nofollow" href="http://singmann.org/new-version-of-rtdists-on-cran-v-0-4-9-accumulator-models-for-response-time-distributions/" target="_blank">previous blog post</a> are wrong). As a temporary fix, we resorted to the correct but slow numerical integration of the PDF (i.e., <code>ddiffusion</code>) to obtain the CDF in version 0.5-2 and later. Importantly, it appears as if the error was not present in  <a rel="nofollow" href="http://www.psychologie.uni-heidelberg.de/ae/meth/fast-dm/" target="_blank"><code>fastdm</code></a> which is the source of the <code>C</code> code we use. Matthew Gretton carefully investigated the original <code>C</code> code, changed it such that it connects to <code>R</code> via <code>Rcpp</code>, and realized that there are two different variants of the CDF, a <code>fast</code> variant and a <code>precise</code> variant. Up to this point we had only used the <code>fast</code> variant and, as it turns out, this was responsible for our incorrect results. We now per default use the <code>precise</code> variant (which only seems to be marginally slower) as it produces the correct results for all cases we have tested (and we have tested quite a few).</p>
<p>In addition to a few more minor changes (see <a rel="nofollow" href="https://cran.rstudio.com/web/packages/rtdists/NEWS" target="_blank">NEWS</a> for full list), we made two more noteworthy changes. First, all diffusion functions as well as <code>rLBA</code> received a major performance update, mainly in situations with trial-wise parameters. Now it should almost always be fastest to call the diffusion functions (e.g., <code>ddiffusion</code>) only once with vectorized parameters instead of calling it several times for different sets of parameters. The speed up with the new version depends on the number of unique parameter sets, but even with only a few different sets the speed up should be clearly noticeable. For completely trial-wise parameters the speed-up should be quite dramatic.</p>
<p>Second, I also updated the <a rel="nofollow" href="https://cran.rstudio.com/web/packages/rtdists/vignettes/reanalysis_rr98.html" target="_blank">vignette</a> which now uses the <a rel="nofollow" href="http://tidyverse.org/" target="_blank"><code>tidyverse</code></a> in, I believe, a somewhat more reasonable manner. Specifically, it now is built on <code>nested</code> data (via <code>tidyr::nest</code>) and <code>purrr::map</code> instead of relying heavily on <code>dplyr::do</code>.  The problem I had with <code>dplyr::do</code> is that it often leads to somewhat ugly syntax. The changes in the vignette are mainly due to me reading <a rel="nofollow" href="http://r4ds.had.co.nz/many-models.html" target="_blank">Chapter 25 in the great <code>R for Data Science</code> book by Wickham and Gorlemund</a>. However, I still prefer <code>lattice</code> over <code>ggplot2</code>.</p>
<h3>Example Analysis</h3>
<p>To show the now correct behavior of the diffusion CDF let me repeat the example from the last post. As a reminder, we somewhat randomly pick one participant from the <code>speed_acc</code> data set <span rel="{ 'api_user_id': '881472', 'pages': '', 'items': '5FS47DBR', 'format': '(%a%, %d%, %p%)', 'brackets': '', 'etal': '', 'separator': '', 'and': '' }"></span> and fit both diffusion model and LBA to the data.</p>
<pre data-enlighter-language="null">require(rtdists)

# Exp. 1; Wagenmakers, Ratcliff, Gomez, &amp; McKoon (2008, JML)
data(speed_acc)   
# remove excluded trials:
speed_acc &lt;- droplevels(speed_acc[!speed_acc$censor,]) 
# create numeric response variable where 1 is an error and 2 a correct response: 
speed_acc$corr &lt;- with(speed_acc, as.numeric(stim_cat == response))+1 
# select data from participant 11, accuracy condition, non-word trials only
p11 &lt;- speed_acc[speed_acc$id == 11 &amp; 
                   speed_acc$condition == &quot;accuracy&quot; &amp; 
                   speed_acc$stim_cat == &quot;nonword&quot;,] 
prop.table(table(p11$corr))
#          1          2 
# 0.04166667 0.95833333 


ll_lba &lt;- function(pars, rt, response) {
  d &lt;- dLBA(rt = rt, response = response, 
            A = pars[&quot;A&quot;], 
            b = pars[&quot;A&quot;]+pars[&quot;b&quot;], 
            t0 = pars[&quot;t0&quot;], 
            mean_v = pars[c(&quot;v1&quot;, &quot;v2&quot;)], 
            sd_v = c(1, pars[&quot;sv&quot;]), 
            silent=TRUE)
  if (any(d == 0)) return(1e6)
  else return(-sum(log(d)))
}

start &lt;- c(runif(3, 0.5, 3), runif(2, 0, 0.2), runif(1))
names(start) &lt;- c(&quot;A&quot;, &quot;v1&quot;, &quot;v2&quot;, &quot;b&quot;, &quot;t0&quot;, &quot;sv&quot;)
p11_norm &lt;- nlminb(start, ll_lba, lower = c(0, -Inf, 0, 0, 0, 0), 
                   rt=p11$rt, response=p11$corr)
p11_norm[1:3]
# $par
#          A         v1         v2          b         t0         sv 
#  0.1182940 -2.7409230  1.0449963  0.4513604  0.1243441  0.2609968 
# 
# $objective
# [1] -211.4202
# 
# $convergence
# [1] 0


ll_diffusion &lt;- function(pars, rt, response) 
{
  densities &lt;- ddiffusion(rt, response=response, 
                          a=pars[&quot;a&quot;], 
                          v=pars[&quot;v&quot;], 
                          t0=pars[&quot;t0&quot;], 
                          sz=pars[&quot;sz&quot;], 
                          st0=pars[&quot;st0&quot;],
                          sv=pars[&quot;sv&quot;])
  if (any(densities == 0)) return(1e6)
  return(-sum(log(densities)))
}

start &lt;- c(runif(2, 0.5, 3), 0.1, runif(3, 0, 0.5))
names(start) &lt;- c(&quot;a&quot;, &quot;v&quot;, &quot;t0&quot;, &quot;sz&quot;, &quot;st0&quot;, &quot;sv&quot;)
p11_diff &lt;- nlminb(start, ll_diffusion, lower = 0, 
                   rt=p11$rt, response=p11$corr)
p11_diff[1:3]
# $par
#         a         v        t0        sz       st0        sv 
# 1.3206011 3.2727202 0.3385602 0.4621645 0.2017950 1.0551706 
# 
# $objective
# [1] -207.5487
# 
# $convergence
# [1] 0</pre>
<p>As is common, we pass the negative summed log-likelihood to the optimization algorithm (here trusty <code>nlminb</code>) and hence lower values of <code>objective</code> indicate a better fit. Results show that the LBA provides a somewhat better account. The interesting question is whether this somewhat better fit translates into a visibly better fit when comparing observed and predicted quantiles.</p>
<pre data-enlighter-language="null"># quantiles:
q &lt;- c(0.1, 0.3, 0.5, 0.7, 0.9)

## observed data:
(p11_q_c &lt;- quantile(p11[p11$corr == 2, &quot;rt&quot;], probs = q))
#    10%    30%    50%    70%    90% 
# 0.4900 0.5557 0.6060 0.6773 0.8231 
(p11_q_e &lt;- quantile(p11[p11$corr == 1, &quot;rt&quot;], probs = q))
#    10%    30%    50%    70%    90% 
# 0.4908 0.5391 0.5905 0.6413 1.0653 

### LBA:
# predicted error rate  
(pred_prop_correct_lba &lt;- pLBA(Inf, 2, 
                               A = p11_norm$par[&quot;A&quot;], 
                               b = p11_norm$par[&quot;A&quot;]+p11_norm$par[&quot;b&quot;], 
                               t0 = p11_norm$par[&quot;t0&quot;], 
                               mean_v = c(p11_norm$par[&quot;v1&quot;], p11_norm$par[&quot;v2&quot;]), 
                               sd_v = c(1, p11_norm$par[&quot;sv&quot;])))
# [1] 0.9581342

(pred_correct_lba &lt;- qLBA(q*pred_prop_correct_lba, response = 2, 
                          A = p11_norm$par[&quot;A&quot;], 
                          b = p11_norm$par[&quot;A&quot;]+p11_norm$par[&quot;b&quot;], 
                          t0 = p11_norm$par[&quot;t0&quot;], 
                          mean_v = c(p11_norm$par[&quot;v1&quot;], p11_norm$par[&quot;v2&quot;]), 
                          sd_v = c(1, p11_norm$par[&quot;sv&quot;])))
# [1] 0.4871710 0.5510265 0.6081855 0.6809796 0.8301286
(pred_error_lba &lt;- qLBA(q*(1-pred_prop_correct_lba), response = 1, 
                        A = p11_norm$par[&quot;A&quot;], 
                        b = p11_norm$par[&quot;A&quot;]+p11_norm$par[&quot;b&quot;], 
                        t0 = p11_norm$par[&quot;t0&quot;], 
                        mean_v = c(p11_norm$par[&quot;v1&quot;], p11_norm$par[&quot;v2&quot;]), 
                        sd_v = c(1, p11_norm$par[&quot;sv&quot;])))
# [1] 0.4684374 0.5529575 0.6273737 0.7233961 0.9314820


### diffusion:
# same result as when using Inf, but faster:
(pred_prop_correct_diffusion &lt;- pdiffusion(rt = 20,  response = &quot;upper&quot;,
                                      a=p11_diff$par[&quot;a&quot;], 
                                      v=p11_diff$par[&quot;v&quot;], 
                                      t0=p11_diff$par[&quot;t0&quot;], 
                                      sz=p11_diff$par[&quot;sz&quot;], 
                                      st0=p11_diff$par[&quot;st0&quot;], 
                                      sv=p11_diff$par[&quot;sv&quot;]))  
# [1] 0.964723

(pred_correct_diffusion &lt;- qdiffusion(q*pred_prop_correct_diffusion, 
                                      response = &quot;upper&quot;,
                                      a=p11_diff$par[&quot;a&quot;], 
                                      v=p11_diff$par[&quot;v&quot;], 
                                      t0=p11_diff$par[&quot;t0&quot;], 
                                      sz=p11_diff$par[&quot;sz&quot;], 
                                      st0=p11_diff$par[&quot;st0&quot;], 
                                      sv=p11_diff$par[&quot;sv&quot;]))
# [1] 0.4748271 0.5489903 0.6081182 0.6821927 0.8444566
(pred_error_diffusion &lt;- qdiffusion(q*(1-pred_prop_correct_diffusion), 
                                    response = &quot;lower&quot;,
                                    a=p11_diff$par[&quot;a&quot;], 
                                    v=p11_diff$par[&quot;v&quot;], 
                                    t0=p11_diff$par[&quot;t0&quot;], 
                                    sz=p11_diff$par[&quot;sz&quot;], 
                                    st0=p11_diff$par[&quot;st0&quot;], 
                                    sv=p11_diff$par[&quot;sv&quot;]))
# [1] 0.4776565 0.5598018 0.6305120 0.7336275 0.9770047


### plot predictions

par(mfrow=c(1,2), cex=1.2)
plot(p11_q_c, q*prop.table(table(p11$corr))[2], pch = 2, ylim=c(0, 1), xlim = c(0.4, 1.3), ylab = &quot;Cumulative Probability&quot;, xlab = &quot;Response Time (sec)&quot;, main = &quot;LBA&quot;)
points(p11_q_e, q*prop.table(table(p11$corr))[1], pch = 2)
lines(pred_correct_lba, q*pred_prop_correct_lba, type = &quot;b&quot;)
lines(pred_error_lba, q*(1-pred_prop_correct_lba), type = &quot;b&quot;)
legend(&quot;right&quot;, legend = c(&quot;data&quot;, &quot;predictions&quot;), pch = c(2, 1), lty = c(0, 1))

plot(p11_q_c, q*prop.table(table(p11$corr))[2], pch = 2, ylim=c(0, 1), xlim = c(0.4, 1.3), ylab = &quot;Cumulative Probability&quot;, xlab = &quot;Response Time (sec)&quot;, main = &quot;Diffusion&quot;)
points(p11_q_e, q*prop.table(table(p11$corr))[1], pch = 2)
lines(pred_correct_diffusion, q*pred_prop_correct_diffusion, type = &quot;b&quot;)
lines(pred_error_diffusion, q*(1-pred_prop_correct_diffusion), type = &quot;b&quot;)
</pre>
<p><img data-orig-file="https://i1.wp.com/singmann.org/wp-content/uploads/2017/05/p11_predictions_correct.png?fit=600%2C400" data-orig-size="600,400" data-medium-file="https://i1.wp.com/singmann.org/wp-content/uploads/2017/05/p11_predictions_correct.png?fit=300%2C200" data-attachment-id="481" data-image-meta="{" data-image-description="" src="https://i1.wp.com/singmann.org/wp-content/uploads/2017/05/p11_predictions_correct.png?resize=490%2C327" data-permalink="http://singmann.org/rtdists-0-7-2-response-time-distributions-now-with-rcpp-and-faster/p11_predictions_correct/" data-large-file="https://i1.wp.com/singmann.org/wp-content/uploads/2017/05/p11_predictions_correct.png?fit=490%2C327" alt="" data-image-title="p11_predictions_correct" sizes="(max-width: 490px) 100vw, 490px" data-comments-opened="1" class="wp-image-481" data-recalc-dims="1"></p>
<p>The fit plot compares observed quantiles (as triangles) with predicted quantiles (circles connected by lines). Here we decided to plot the 10%, 30%, 50%, 70% and 90% quantiles. In each plot, the x-axis shows RTs and the y-axis cumulative probabilities. From this it follows that the upper line and points correspond to the correct trials (which are common) and the lower line and points to the incorrect trials (which are uncommon). For both models the fit looks pretty good especially for the correct trials. However, it appears the LBA does a slightly better job in predicting very fast and slow trials here, which may be responsible for the better fit in terms of summed log-likelihood. In contrast, the diffusion model seems somewhat better in predicting the long tail of the error trials.</p>
<h3>Checking the CDF</h3>
<p>Finally, we can also check whether the analytical CDF does in fact correspond to the empirical CDF of the data. For this we can compare the analytical CDF function <code>pdiffusion</code> to the empirical CDF obtained from random deviates. One thing one needs to be careful about is that <code>pdiffusion</code> provides the ‘defective’ CDF that only approaches one if one adds the CDF for both response boundaries. Consequently, to compare the empirical CDF for one response with the analytical CDF, we need to scale the latter to also go from 0 to 1 (simply by dividing it by its maximal value). Here we will use the parameters values obtained in the previous fit.</p>
<pre data-enlighter-language="null">rand_rts &lt;- rdiffusion(1e5, a=p11_diff$par[&quot;a&quot;], 
                            v=p11_diff$par[&quot;v&quot;], 
                            t0=p11_diff$par[&quot;t0&quot;], 
                            sz=p11_diff$par[&quot;sz&quot;], 
                            st0=p11_diff$par[&quot;st0&quot;], 
                            sv=p11_diff$par[&quot;sv&quot;])
plot(ecdf(rand_rts[rand_rts$response == &quot;upper&quot;,&quot;rt&quot;]))

normalised_pdiffusion = function(rt,...) pdiffusion(rt,...)/pdiffusion(rt=Inf,...) 
curve(normalised_pdiffusion(x, response = &quot;upper&quot;,
                            a=p11_diff$par[&quot;a&quot;], 
                            v=p11_diff$par[&quot;v&quot;], 
                            t0=p11_diff$par[&quot;t0&quot;], 
                            sz=p11_diff$par[&quot;sz&quot;], 
                            st0=p11_diff$par[&quot;st0&quot;], 
                            sv=p11_diff$par[&quot;sv&quot;]), 
      add=TRUE, col = &quot;yellow&quot;, lty = 2)</pre>
<p><img data-orig-file="https://i1.wp.com/singmann.org/wp-content/uploads/2017/05/p11_CDF_check.png?fit=600%2C400" data-orig-size="600,400" data-medium-file="https://i1.wp.com/singmann.org/wp-content/uploads/2017/05/p11_CDF_check.png?fit=300%2C200" data-attachment-id="496" data-image-meta="{" data-image-description="" src="https://i1.wp.com/singmann.org/wp-content/uploads/2017/05/p11_CDF_check.png?resize=490%2C327" data-permalink="http://singmann.org/rtdists-0-7-2-response-time-distributions-now-with-rcpp-and-faster/p11_cdf_check/" data-large-file="https://i1.wp.com/singmann.org/wp-content/uploads/2017/05/p11_CDF_check.png?fit=490%2C327" alt="" data-image-title="p11_CDF_check" sizes="(max-width: 490px) 100vw, 490px" data-comments-opened="1" class="wp-image-496" data-recalc-dims="1"></p>
<p>This figure shows that the analytical CDF (in yellow) lies perfectly on top the empirical CDF (in black). If it does not for you, you still use an old version of <code>rtdists</code>. We have also added a series of unit tests to <code>rtdists</code> that compare the empirical CDF to the analytical CDF (using <code>ks.test</code>) for a variety of parameter values to catch if such a problem ever occurs again.</p>
<h4>References</h4>
<div>
<span>881472</span><br>
<span>{QQ2QRTIF};{4MC596NZ};5FS47DBR</span><br>
<span>apa</span><br>
<span>default</span><br>
<span>ASC</span><br>
<span>no</span><br>
<span></span><br>
<span></span><br>
<span></span><br>
<span></span><br>
<span></span><br>
<span></span><br>
<span></span><br>
<span></span><br>
<span></span><br>
<span></span><br>
<span>475</span><br>
<span>http://singmann.org/wp-content/plugins/zotpress/</span>
<div></div>
<p></div>
<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/rtdists-0-7-2-response-time-distributions-now-with-rcpp-and-faster/"> R-bloggers – Henrik Singmann – Computational Psychology</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/wSNhzez04BQ" height="1"></a></div>