title: Summation in R inside function
body: <p>I'm writing a function in R that has to compute the values of two vectors before going ahead and doing some other fancy stuff. The two vectors, R and B, are given by the following summations:</p>
  
  <p><img src="https://i.stack.imgur.com/jppX5.gif" alt="enter image description here"></p>
  
  <p>and </p>
  
  <p><img src="https://i.stack.imgur.com/Qs4Hy.gif" alt="$$ R(i)=\sum_{k=1}^{i-1}(t_i-t_k)e^{-\beta(t_i-t_k)} $$"></p>
  
  <p>where $\beta$ is a constant and the <em>ts</em> are passed to the function and are the occurrence times of an event. So, basically, when the i-th event occurs (at time <code>t_i</code>), I compute <code>B(i)</code> and <code>R(i)</code> which are summations done using all the previous occurrence times <code>t_k</code> of my event up to that moment.</p>
  
  <p>I would like to come up with something more efficient than this </p>
  
  <pre><code>r &lt;- rep(0,length(t))
  for(i in 2:length(t)) {
      r[i] &lt;- sum((t[i]-t[which(t&lt;t[i])])*exp(beta*(t[i]-t[which(t&lt;t[i])])))
  }
  b &lt;- rep(0,length(t))
  for(i in 2:length(t)) {
      b[i] &lt;- sum(((t[i]-t[which(t&lt;t[i])])^2)*exp(beta*(t[i]-t[which(t&lt;t[i])])))
  }
  </code></pre>
  
  <p>which basically computes everything twice even though the only difference between the two is the square before the exponential. Any ideas? Thanks!</p>