Murali Murali - 1 year ago 65
R Question

Determine Sales trend with multiple variables like Customer ID/Item etc

I got stuck while working on trends. My problem is similar to this below thread but I have one extra variable called 'item'.

how to determine trend of a series of values in R

My end result would be like below sample. Please help

Customer_ID Item Sales_Slope
Josh milk Positive
Josh eggs Negative
Eric milk Mixed
Eric eggs postive

My Data:

dat <- data.table(

dat[,transaction_num:=seq(1,.N), by=c("customer_ID")]

Answer Source

And the data.table approach which I outlined was:


trend <- function(x) {
   ifelse(all(diff(x)>0), 'Positive',
   ifelse(all(diff(x)<0), 'Negative', 'Mixed'))

dat[, trend(sales), by=c("customer_ID","item")]
   customer_ID item       V1
1:        Josh milk Positive
2:        Josh eggs Negative
3:         Ray milk    Mixed
4:         Ray eggs Positive
5:        Eric milk Negative
6:        Eric eggs    Mixed

# or if you want to assign the result...
dat[, Sales_Slope:=trend(sales), by=c("customer_ID","item")]