You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为R的data.table生成累积乘积列factorcumulative?求简洁实现方案

实现方法

当然有简洁优雅的实现方式,利用data.table的**累积乘积函数cumprod()**配合其专属的赋值操作符:=,一行代码就能完成需求:

直接在原表新增列

DT[, factorcumulative := cumprod(factor)]

这样会直接在原DT对象中添加factorcumulative列,不需要额外创建临时对象。

生成新表保留原表不变

如果不想修改原DT,可以先复制原表再操作:

DT2 <- copy(DT)[, factorcumulative := cumprod(factor)]

或者直接通过选择列的方式生成新表:

DT2 <- DT[, .(Year, factor, factorcumulative = cumprod(factor))]

cumprod(factor)会自动计算factor列的累积乘积,正好对应你需要的0.9, 0.9*0.8, 0.9*0.8*0.7结果,完全符合需求。

内容的提问来源于stack exchange,提问作者highbury

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 17:22:03