From a question I asked before (Count with conditions in R dataframe), I have the following table:
Week SKU Discount(%) Duration LastDiscount
1 111 5 2 0
2 111 5 2 0
3 111 0 0 0
4 111 10 2 0
5 111 11 2 2
1 222 0 0 0
2 222 10 3 0
3 222 15 3 0
4 222 20 3 0
I want the LastDiscount
count to be in the first row where there is a different discount for the same SKU in different weeks. For example, the SKU 111 had a discount in the 2nd week and the next discount is in the 4th week, that gives 2 weeks since the last discount but the problem is that I want the result to be in the 4th week where starts the next discount campaign.
Something like this:
Week SKU Discount(%) Duration LastDiscount
1 111 5 2 0
2 111 5 2 0
3 111 0 0 0
4 111 10 2 2
5 111 11 2 0
1 222 0 0 0
2 222 10 3 0
3 222 15 3 0
4 222 20 3 0
I have this code right now:
df1 %>%
group_by(SKU) %>%
mutate(Duration = with(rle(Discount > 0), rep(lengths*values,
lengths)),
temp = with(rle(Discount > 0), sum(values != 0)),
LastDiscount = if(temp[1] > 1) c(rep(0, n()-1), temp[1]) else 0) %>%
select(-temp)