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:

![enter image description here](https://i.stack.imgur.com/jppX5.gif)

and 

![$$ R(i)=\sum_{k=1}^{i-1}(t_i-t_k)e^{-\beta(t_i-t_k)} $$](https://i.stack.imgur.com/Qs4Hy.gif)

where $\beta$ is a constant and the *ts* are passed to the function and are the occurrence times of an event. So, basically, when the i-th event occurs (at time `t_i`), I compute `B(i)` and `R(i)` which are summations done using all the previous occurrence times `t_k` of my event up to that moment.

I would like to come up with something more efficient than this 

```
r <- rep(0,length(t))
for(i in 2:length(t)) {
    r[i] <- sum((t[i]-t[which(t<t[i])])*exp(beta*(t[i]-t[which(t<t[i])])))
}
b <- rep(0,length(t))
for(i in 2:length(t)) {
    b[i] <- sum(((t[i]-t[which(t<t[i])])^2)*exp(beta*(t[i]-t[which(t<t[i])])))
}

```

which basically computes everything twice even though the only difference between the two is the square before the exponential. Any ideas? Thanks!