# 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

system("ls ../input")

# Any results you write to the current directory are saved as output.
clicks <- read.csv("../input/clicks_test.csv")

sortc <- clicks[order(clicks$ad_id),]

agreegate <- as.data.frame(table(sortc$ad_id))

names(agreegate) <- c("ad_id", "count")

join <- merge(x = sortc, y = agreegate, by = "ad_id")

sorti <- join[order(join$display_id,-join$count ),c("display_id","ad_id","count")]

final <- sorti[!duplicated(sorti[, c("display_id")]),c("display_id","ad_id") ]