# 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(Matrix)
library(plyr)
library(usdm)
library(data.table)
library(stringr)
library(httr)
library(readr)
library(stringr)
library(bit64)

# 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")

# Any results you write to the current directory are saved as output.
set.seed(1234)
chunks<-4
# Load Datasets -----------------------------------------------------------
gc()
train <- fread("../input/train.csv")
#View(train[1:10000])
#train$place_id<-substr(train$place_id,start=316,stop=330)
#count(unique(train$place_id))
#setkey(train,srch_destination_id)
test  <- fread("../input/test.csv")
#train1<-train[1:1000]
train1<-train[,list(mean_x=mean(x),sd_x=sd(x),mean_y=mean(y),sd_y=sd(y),mean_acc=mean(accuracy),sd_acc=sd(accuracy)),by=place_id]
#train<-train1
#rm(train1)
setkey(train1,mean_y)
test1<-test
setkey(test1,y)
#setattr(train,"sorted","mean_y")
train2<-train1[J(test1), roll = "nearest"]
nrow(unique(train2))
train3<-train2[,c("row_id","place_id"),with=FALSE]
train4<-train3[,list(place_id=max(place_id)),by=row_id]
final<-train1[J(test1), .I, roll = "nearest", by = .EACHI]
nrow(unique(train3))
write.csv(train4,"subm_1.csv",row.names=FALSE)
