I'm trying to calculate favorite brand per productcategory per customer.
1. Start and what I want to achieve
I start with a dataframe (mydata) with purchase orders, build up like this:
| customer | ordernumber | productcategory | brand | amount |
|---|---|---|---|---|
| ABC | 123456 | H11_plumbing | Nitrofill | 6 |
| ABC | 123457 | H11_plumbing | Antileak | 2 |
| DEF | 123458 | H11_plumbing | Nitrofill | 1 |
| DEF | 123459 | H11_plumbing | Antileak | 5 |
| ABC | 123460 | H12_electric | Shock | 10 |
| ABC | 123461 | H12_electric | Lightning | 5 |
| DEF | 123462 | H12_electric | Shock | 4 |
| DEF | 123463 | H12_electric | Lightning | 8 |
What I want to achieve is list per customer the favorite brand per productcategory.
| customer | H11_plumbing_favorite_brand | H12_electric_favorite_brand |
|---|---|---|
| ABC | Nitrofill | Shock |
| DEF | Antileak | Lightning |
For customer ABC Nitrofill (amount = 6) and Shock (amount = 10) are favorites
2. What I am doing now
What I now did was create a list of vectors for each productcategory and change the shape from long to wide using lapply to use data.table::dcast
df_list <- split(mydata, as.factor(mydata$productcategory)) # create list of vectors
library(data.table)
df_list_2 <- lapply(df_list,function(x) x <- data.table::dcast(setDT(x), customer ~ brand, sum, value.var = c("amount"))) # change shape from long to wide
3. Where I get stuck is finding and returning the column with the favorite brand
This is where I get stuck. I have been able to do this for a data.frame (vector) rather than a list of vectors by using this code:
mydata_t <- mydata[mydata$productcategory=="H12_electric",]
mydata_overview<- data.table::dcast(setDT(mydata_t), customer ~ brand, sum, value.var = c("amount"))
rm(mydata_t)
mydata_overview$favorite_brand <- apply(mydata_overview[,-c(1)],1,function(x) which(x==max(x)))
However, if I try to use this code on the list of vectors (df_list) then it doesn't work.
df_list_3 <- lapply(df_list,function(x) x$favorite_brand<- apply(x[,-c(1)],1,function(y) which(y==max(y))))
rm(df_list_t)
Any suggestions?