如何使用data.table滚动产品 [英] How do I take a rolling product using data.table

查看:84
本文介绍了如何使用data.table滚动产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

dt <- data.table(x=c(1, .9, .8, .75, .5, .1))
dt
      x
1: 1.00
2: 0.90
3: 0.80
4: 0.75
5: 0.50
6: 0.10

对于每一行,我如何得到该行的x和下两行的乘积?

For each row, how do I get the product of x for that row and the next two rows?

      x Prod.3
1: 1.00 0.7200
2: 0.90 0.5400
3: 0.80 0.3000
4: 0.75 0.0375
5: 0.50     NA
6: 0.10     NA

,对于每一行,我如何得到该行和下一行

More generally, for each row, how do I get the product of x for that row and the next n rows?

推荐答案

您可以尝试

library(zoo)
rollapply(dt, 3, FUN = prod)
          x
[1,] 0.7200
[2,] 0.5400
[3,] 0.3000
[4,] 0.0375

匹配预期输出

dt[, Prod.3 :=rollapply(x, 3, FUN=prod, fill=NA, align='left')]

这篇关于如何使用data.table滚动产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆