在R中滚动产品?

时间:2019-05-08 15:28:15

标签: r

x <- as.data.frame(1:5)

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

1*2*3*4*5 = 120 then
2*3*4*5 = 120 then
3*4*5 = 60

以此类推。

如何在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

2 个答案:

答案 0 :(得分:5)

我们可以使用cumprod

rev(cumprod(rev(x[[1]])))
#[1] 120 120  60  20   5

rev(Reduce(`*`, rev(x[[1]]), accumulate = TRUE))

此外,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

答案 1 :(得分:1)

为此,您只需在数据中添加一个新列即可

data <- data.frame(list(x = 1:5))
data
  x
1 1
2 2
3 3
4 4
5 5
data$prod <- apply(data,1,function(x) prod(x:5))
  data
  x prod
1 1  120
2 2  120
3 3   60
4 4   20
5 5    5