multiply each element in a vector by the next element[r]

Viewed 418
vector=c(1.007469, 1.007469, 1.007369, 1.007419, 1.007269, 1.007769, 1.007969, 1.007469, 1.007469 ,1.007469, 1.007469, 1.007469, 1.004469, 1.007469, 1.007469, 1.006469, 1.007469 ,1.007469 ,1.007469 ,1.007469 ,1.007869 ,1.007469 ,1.007469 ,1.007469 ,1.007469, 1.007469,
 1.007469, 1.007469 ,1.007469, 1.007469)

I was trying to find the accumulated interest rates, for that I need to add 1, in each rate(I already did that and saved it to the vector object), and multiply each one by the next, after that (result_vector-1)* 100 in the result, how to multiply the first element of a vector by the next and etc?

2 Answers

We can use cumprod if we need to return a vector of the same length with each value multiplied by the previous multiplied values.

cumprod(vector-1)

If we need to return a single product, then use prod

prod(vector-1)

Or with Reduce and *

Reduce(`*`, vector-1)

You can also use a for loop:

v <- c(1.007469, 1.007469, 1.007369, 1.007419, 1.007269, 1.007769, 1.007969, 1.007469, 1.007469 ,1.007469, 1.007469, 1.007469, 1.004469, 1.007469, 1.007469, 1.006469, 1.007469 ,1.007469 ,1.007469 ,1.007469 ,1.007869 ,1.007469 ,1.007469 ,1.007469 ,1.007469, 1.007469,
 1.007469, 1.007469 ,1.007469, 1.007469)

res <- -100
for(i in 1:length(v)) {
    res <- res * v[i]
}
print(res)

cumulative_v = -100 * cumprod(v)
stopifnot(all.equal(res, cumulative_v[length(cumulative_v)]))

Output:

[1] -124.6208
Related