0

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)]
}
5
  • 1
    I think your C-CumSales is incorrect, based on your input Commented Apr 11, 2017 at 16:03
  • 2
    Well, you can put parentheses, like (i) :=. Commented Apr 11, 2017 at 16:10
  • 1
    @Frank You are right. I think i meant 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][] Commented Apr 11, 2017 at 16:18
  • @akrun Thank you for noticing. I fixed it. Commented Apr 11, 2017 at 16:46
  • @Frank Thank you for your solution! Commented Apr 11, 2017 at 16:59

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.