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
我们可以用 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句