Calculate product of all following vector elements in R

Viewed 109

I have some arbitrary vector such as

v <- seq(1,5)

For every index of v I now need to compute the product of all following elements of v.

Here, the result would be a vector w=(5*4*3*2,5*4*3,5*4,5,1) but I need a general algorithm for this. I am trying to avoid a loop (which is the obvious solution).

1 Answers

You can use cumprod with rev:

c(rev(cumprod(rev(v[-1]))), 1)
#[1] 120  60  20   5   1
Related