Understanding R convolution code with sapply() <p>I am trying to break apart the R code in <a href="http://stats.stackexchange.com/a/41263/67822">this post</a>:</p> <pre><code>x &lt;- c(0.17,0.46,0.62,0.08,0.40,0.76,0.03,0.47,0.53,0.32,0.21,0.85,0.31,0.38,0.69) convolve.binomial &lt;- function(p) { # p is a vector of probabilities of Bernoulli distributions. # The convolution of these distributions is returned as a vector # `z` where z[i] is the probability of i-1, i=1, 2, ..., length(p)+1. n &lt;- length(p) + 1 z &lt;- c(1, rep(0, n-1)) sapply(p, function(q) {z &lt;&lt;- (1 - q) * z + q * (c(0, z[-n])); q}) z } convolve.binomial(x) [1] 5.826141e-05 1.068804e-03 8.233357e-03 3.565983e-02 9.775029e-02 [6] 1.804516e-01 2.323855e-01 2.127628e-01 1.394564e-01 6.519699e-02 [11] 2.141555e-02 4.799630e-03 6.979119e-04 6.038947e-05 2.647052e-06 [16] 4.091095e-08 </code></pre> <p>I tried <code>debugging</code> in RStudio, but it still opaque.</p> <p>The issue is with the line: <code>sapply(p, function(q) {z &lt;&lt;- (1 - q) * z + q * (c(0, z[-n])); q})</code>.</p> <p>I guess that within the context of the call <code>convolve.binomial(x)</code> <code>p = q = x</code>. At least I get identical results if I pull the lines outside the function and run <code>sapply(x, function(x) {z &lt;&lt;- (1 - x) * z + x * (c(0, z[-n])); x}) </code>:</p> <pre><code>x &lt;- c(0.17,0.46,0.62,0.08,0.40,0.76,0.03,0.47,0.53,0.32,0.21,0.85,0.31,0.38,0.69) n &lt;- length(x) + 1 z &lt;- c(1, rep(0, n-1)) # [1] 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 sapply(x, function(x) {z &lt;&lt;- (1 - x) * z + x * (c(0, z[-n])); x}) z # Is extracted by calling it and contains the correct result </code></pre> <hr> <p>My questions are:</p> <ol> <li>What is the purpose of the <code>;q}</code> ending within <code>sapply()</code>?</li> <li>How does it relate to the <code>&lt;&lt;-</code> symbol, meant to make <code>z</code> accessible outside of the "implicit" loop that is <code>sapply()</code>?</li> </ol> <hr> <p>Below you can see my problem "hacking" this line of code:</p> <pre><code>(x_complem = 1 - x) sapply(x, function(x) {z &lt;&lt;- x_complem * z + x * (c(0, z[-n])); x}) z # Returns 16 values and warnings z_offset = c(0, z[-n]) # [1] 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 sapply(x, function(x) {z &lt;&lt;- (1 - x) * z + x * z_offset; x}) z # Returns different values. </code></pre>