# This R environment comes with all of CRAN preinstalled, as well as many other helpful packages
# The environment is defined by the kaggle/rstats docker image: https://github.com/kaggle/docker-rstats
# For example, here's several helpful packages to load in 

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

# Input data files are available in the "../input/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory

system("ls ../input")




#import train data
sampleData <- read.csv("../input/train.csv", header = TRUE, nrows = 5, sep=",")
classes <- sapply(sampleData, class)
largeData <- read.csv("../input/train.csv", header = TRUE, colClasses = classes, nrows=200000)
str(largeData)

#import test data
testSampleData <- read.csv("../input/test.csv", header = TRUE, nrows = 5, sep=",")
classes <- sapply(testSampleData, class)
testLargeData <- read.csv("../input/test.csv", header = TRUE, colClasses = classes)
str(testLargeData)

#create model
t0 <- Sys.time()
#modFit <- train(Demanda_uni_equil ~ .,method="gbm",data=largeData, verbose=FALSE)
modFit <- train(Demanda_uni_equil ~ Semana + Agencia_ID+Canal_ID+Ruta_SAK+Cliente_ID+Producto_ID,method="gbm",data=largeData, verbose=FALSE)
print(modFit)
t1 <- Sys.time()
t1-t0

#create prediction
prediction <- predict(modFit, newdata = testLargeData)
t2 <- Sys.time()
t2-t1
str(prediction)

#fix negatives
prediction[prediction<0] = 0.01

#create submission file
submission <- data.frame(ID=testLargeData$id, Demanda_uni_equil=prediction)
write.csv(submission, "submission.csv", row.names = F)

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