# Load required packages ---------------------------------------------------

library(ggplot2)
library(reshape2)

#Turn off scientific notation

options(scipen = 999)

# Generate dataset before-after analysis -----------------------------------
n=40 #has to be an even number for the later code to run correctly
set.seed(1234)
search_data <- data.frame(c(1:n), c(rep(1, times=n/2),rep(0, times=n/2)))

names(search_data)[1] <- paste("Week")
names(search_data)[2] <- paste("SEA_on")

search_data$Paid_volume <- ifelse(search_data$SEA_on==1, 
                                  25000+sample(0:5000, n), 
                                  0)

search_data$Organic_volume <- ifelse(search_data$SEA_on==1, 
                                     search_data$Paid_volume*1.5 + 10000 + sample(0:5000, n), 
                                     67500 + sample(5000))


# Create total traffic variable
search_data$Total_volume <- search_data$Paid_volume + search_data$Organic_volume


# Create plot of total, organic and paid traffic
dd = search_data[,c(1,3:5)]
dd = melt(dd, id=c("Week"))
colnames(dd)[3] <- "Volume"

ggplot(dd) + geom_line(aes(x=Week, y=Volume, colour=variable)) +
  scale_colour_manual(values=c("red","green","blue"))

rm(dd)
rm(n)


# Load package to make an output table of all models
library(sjPlot)
library(sjmisc)
library(sjlabelled)

#regression models before-after analysis
before_after_model1 <- lm(Total_volume ~ SEA_on, data=search_data)

before_after_model2 <- lm(Total_volume ~ SEA_on + Week, data=search_data)

before_after_model3 <- lm(Organic_volume ~ SEA_on, data=search_data)

before_after_model4 <- lm(Organic_volume ~ SEA_on + Week, data=search_data)

tab_model(before_after_model1, before_after_model2, before_after_model3, 
          before_after_model4, collapse.ci = TRUE, p.style = "stars")


# Mean amount of Paid clicks (i.e. variable 3 in our dataset) when SEA is on
mean(search_data[search_data$SEA_on==1,3])
