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)]
}
Here is what I tried based on the OP's code:
dt <- dt[, .(Product, Sales)]
plevels <- levels(dt$Product)
dt[, c(paste(plevels, 'CumSales', sep = '-')) :=
lapply(plevels, function(x) cumsum(Sales * (Product == x)))]
# Product Sales A-CumSales B-CumSales C-CumSales
# 1: A 10 10 0 0
# 2: B 5 10 5 0
# 3: A 10 20 5 0
# 4: A 20 40 5 0
# 5: B 10 40 15 0
# 6: C 5 40 15 5
# 7: C 5 40 15 10
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.