简体   繁体   中英

R: Cumulative weighted mean in data.table

Basis is the following data 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

Now I would like to calculate the weighted mean for each position, taking into account all positions "<=" the current position. The result should be:

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

Any idea how to do achieve this efficiently?

Assuming your Position column contains unique values and has been sorted before hand, you can calculate based on the definition of weighted average. If Volume is the weight factor:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM