This is what my data.table looks like. The three rightmost columns are my desired columns.
library(data.table)
dt <- fread('
Product Sales A-CumSales B-CumSales C-CumSales
A 10 10 0 0
B 5 10 5 0
A 10 20 5 0
A 20 40 5 0
B 10 40 15 0
C 5 40 15 5
C 5 40 15 10
')
dt[, Product:= as.factor(Product)]
The levels in my Product column are always changing. I am trying to do a loop where I am creating a separate column for each Product that computes the cumulative Sales of the respective Product.
I have tried:
for (i in levels(dt$Product)) {
dt[,i:= cumsum((Product == "i") * Sales)]
}
(i) :=.dcast(dt[, 1:2, with = FALSE], Product + 1:nrow(dt) + rowid(Product)~Product,value.var = "Sales", fill = 0)[, c("A", "B", "C") := lapply(.SD, cumsum), .SDcols = A:C][]