在R中滚动产品?

use*_*484 3 r

x <- as.data.frame(1:5)
Run Code Online (Sandbox Code Playgroud)

与上面的数据框,我想创建一个具有正在运行的产品的新列,即第一个元素应该是

1*2*3*4*5 = 120 then
2*3*4*5 = 120 then
3*4*5 = 60
Run Code Online (Sandbox Code Playgroud)

等等。

我如何在R中做到这一点?

结果应该是

> x[,"result"] <- c(120,120,60,20,5)
> x
  1:5 result
1   1    120
2   2    120
3   3     60
4   4     20
5   5      5
Run Code Online (Sandbox Code Playgroud)

akr*_*run 5

我们可以用 cumprod

rev(cumprod(rev(x[[1]])))
#[1] 120 120  60  20   5
Run Code Online (Sandbox Code Playgroud)

要么

rev(Reduce(`*`, rev(x[[1]]), accumulate = TRUE))
Run Code Online (Sandbox Code Playgroud)

另外,里面有一个方便的包装器 accumulate

library(tidyverse)
x %>% 
   mutate(result = accumulate(`1:5`, `*`, .dir = "backward"))
#  1:5 result
#1   1    120
#2   2    120
#3   3     60
#4   4     20
#5   5      5
Run Code Online (Sandbox Code Playgroud)