R:data.table 中的累积加权平均值

R: Cumulative weighted mean in data.table

基础是以下数据table:

library(data.table)
dt <- data.table(Position = 1:3, Price = c(50, 45, 40), Volume = c(10, 10, 10))

dt
   Position Price Volume
1:        1    50     10
2:        2    45     10
3:        3    40     10

现在我想计算每个位置的加权平均值,同时考虑所有位置 "<=" 当前位置。结果应该是:

dt[, Vwa := c(50, 47.5, 45)]

dt
   Position Price Volume  Vwa
1:        1    50     10 50.0
2:        2    45     10 47.5
3:        3    40     10 45.0

知道如何有效地做到这一点吗?

假设您的 Position 列包含唯一值并且事先已经排序,您可以根据加权平均值的定义进行计算。如果Volume是权重因子:

dt[, Vwa := cumsum(Price * Volume)/cumsum(Volume)]
dt
#   Position Price Volume  Vwa
#1:        1    50     10 50.0
#2:        2    45     10 47.5
#3:        3    40     10 45.0