

library(ggplot2) # Data visualization
library(readr) # CSV file I/O, e.g. the read_csv function
library(data.table)

system("ls ../input")

# Any results you write to the current directory are saved as output.

train <- fread('../input/train.csv', 
               select = c( 'Agencia_ID', 'Producto_ID', 'Cliente_ID', 'Demanda_uni_equil'),
               colClasses=c(Producto_ID="numeric", Agencia_ID="numeric", Cliente_ID="numeric",Demanda_uni_equil="numeric"))

test <- fread('../input/test.csv', 
              select = c('id', 'Agencia_ID', 'Producto_ID', 'Cliente_ID'))
# set a table key to enable fast aggregations
setkey(train, Agencia_ID, Producto_ID,  Cliente_ID)
head(train)
head(test)
#get mean by P,A,C
mean_byPAC <-  train[, .(MPAC = mean(Demanda_uni_equil)), by = .(Producto_ID, Agencia_ID,Cliente_ID)]
head(mean_byPAC)
#get mean by P,C 
mean_byAC <-  train[, .(MAC = mean(Demanda_uni_equil)), by = .(Producto_ID,Cliente_ID)]
mean<- train[, .(MAC = mean(Demanda_uni_equil))]

submit <- merge(test, mean_byPAC, all.x = TRUE, by = c("Agencia_ID", "Cliente_ID", "Producto_ID"))
submit[is.na(MPAC)]$MPAC <- 7

print("writing submission file")

setnames(submit,"MPAC","Demanda_uni_equil")

write.csv(submit[,.(id,Demanda_uni_equil)],"submit_mean_by_Agncy_Prod_Cli.csv", row.names = FALSE)
print("Done!")