# 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
# 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
library(data.table)
get_probs <- function (dt,var,target,w){
  p=dt[,sum(get(target))/.N]
  dt[ ,.( prob=(sum(get(target))+w*p )/(.N+w) ),by=eval(var)]
}
DT_fill_NA <- function(DT,replacement=0.01) {
  for (j in seq_len(ncol(DT)))
    set(DT,which(is.na(DT[[j]])),j,replacement)
}
super_fread <- function( file , key_var=NULL){
  dt <- fread(file)
  if(!is.null(key_var)) setkeyv(dt,c(key_var))
  return(dt)
}

events <- fread("../input/events.csv",
                select=c("display_id","platform"),
                colClasses=c(rep("numeric",4),"character","numeric"))
events[platform < "1",platform:="2"]
setkeyv(events,"display_id")
clicks_train  <- super_fread( "../input/clicks_train.csv", key_var = "display_id" )
clicks_train <- merge( clicks_train, events, all.x = T )
clicks_train[,ad_id_pl:= paste0(ad_id,'_',platform)]
setkeyv(clicks_train,"ad_id_pl")
click_prob = clicks_train[,.(sum(clicked)/.N)]
clicks_train
click_prob
# Any results you write to the current directory are saved as output.