############### ###############
## startable.R
## Project: CBO
## Author: Kamil Kouhen
## Date of creation: 01/05/2022
############### ###############

# Standardized stargazer regression table for publication

startable <- function(models = list(), #list of models to be used, if cbo_regression2 was used before, the list will be found in the environment as ("lm.modelname1" etc.), add them as a list in the form: list("lm..modelname1" = lm..modelname1, "lm..modelname2" = lm..modelname2)
                      FE.yesno = NULL, #If want to display whether FE were used, insert combination in order, e.g.: c("Yes", "No", "Yes")
                      tabtitle = "",
                      tabnote = NULL,
                      control.meanTF = TRUE, #List of control group mean for all outcome variables, in the following format: c(control.mean.modelname1, control.mean.modelname2)
                      outcome.labels = "", #To change outcome variable label in the following format: c("outcome1", "outcome2")
                      indep.tokeep = NULL, #Selecting independent variables to keep (treatment variables for most of the time) in the following format: e.g. c("treat", "treated.commune")
                      indep.labels = NULL, #To change indep variables labels in the following format: c("outcome1", "outcome2")
                      landscape = FALSE, #Whether table output is in landscape format (usepackage(rotating)) on latex
                      display.model = TRUE, #Adding row specifying type of model (OLS, LOGIT etc...)?
                      adjustbox = TRUE, #Using the adjustbox package to fit table in page?
                      label = "" #Labelling table for referencing
){

  #Creating list of the models
  model.list <- models

  ##Need to pass the arguments of Stargazer to this list
  #Aesthetic adjustments
  model.list$style <- "default" #Style of table
  model.list$single.row <- TRUE #No space between line
  model.list$omit.stat <- c("rsq", "adj.rsq", "f", "ser", "ll", "aic")

  if (display.model == TRUE | missing(display.model)){
    model.list$model.names <- TRUE #Model name (OLS, logit etc.) included
  }
  if (display.model == FALSE){
    model.list$model.names <- FALSE #Model name (OLS, logit etc.) not included
  }

  model.list$notes.align <- "l" #Notes aligned to the left
  model.list$single.row <- FALSE #Standard errors under coefficients
  #model.list$column.sep.width <- "-5" #Reduct space between columns
  model.list$font.size <- "footnotesize"
  model.list$digits <- 2
  model.list$no.space <- TRUE

  #Adding number of observations

  if (landscape == TRUE){
    model.list$float.env <- "sidewaystable" #Landscape table instead of portrait table
  }

  #If need to specify FEs
  if (!missing(FE.yesno) & !is.null(FE.yesno)){
    model.list$add.lines <- list(c("Fixed effects?", FE.yesno)
    )
  }

  #List of control means if specified
  if (control.meanTF == TRUE){
    ctrlmean <- paste0("control.mean.", names(models))
    ctrlmean <- lapply(ctrlmean, function(x) eval(parse(text = x)))
    model.list$add.lines <- append(model.list$add.lines, list("Control means" = c("Mean of Control Group", as.vector(unlist(ctrlmean))))) #Adding to list of add-ons (FE etc.)
  }

  #Number of observations
  obser <- paste0("nobs(", names(models), ")")
  obser <- lapply(obser, function(x) eval(parse(text = x)))
  model.list$add.lines <- append(model.list$add.lines, list("Sample size" = c("Sample size", as.vector(unlist(obser))))) #Adding to list of add-ons (FE etc.)

  #If need to specify note
  if (!missing(tabnote) & !is.null(tabnote)){
    model.list$notes <- tabnote
  }

  #For robust standard errors, need to create list with what was return from coeftest in each listed regression
  tabSE2 <- paste0(names(models), "[,'Std. Error']")
  model.list$se <- lapply(tabSE2, function(x) eval(parse(text = x)))

  #Changing outcome variable names
  model.list$column.labels = outcome.labels

  model.list$dep.var.labels.include <- TRUE
  model.list$dep.var.caption <- "" #No need to specify that the the variables are dependent variables

  #Selecting independent variables to keep (treatment variables for most of the time)
  if (missing(indep.tokeep)){
    stop("Error: please select the independent variables to keep. For the CBO, in most cases, they should be the commune and CBO level treatment assignment")
    break
  }
  if (!missing(indep.tokeep) & !is.null(indep.tokeep)){
    model.list$keep = indep.tokeep
  }

  if (!missing(indep.labels) & !is.null(indep.labels)){
    model.list$covariate.labels = indep.labels
  }

  #Title and label for referencing
  ttl <- tabtitle #inputing below when modifying top of latex code
  lbl <- label

  ##Adjusting the stargazer output (removing unnecessary info at the top and adding a package to fit the table in a page)

  #print(model.list)
  output <- capture.output(do.call(stargazer, model.list)) #mod_stargazer created above)

  output <- output[8:length(output)] # The first four lines are the ones we want to remove... (including \begin{table}[!htbp] \centering that will be added again manually)

  output <- output[1:(length(output) - 2)] # Removing last lines (\end{table} & \end{tabular}), I will change them and re-add them

  top1 <- paste0("\\begin{table}[!htbp] \\centering")
  top2 <- paste0("\\caption{", ttl, "}")
  top3 <- paste0("\\label{", lbl, "}")
  top4 <- paste0("\\footnotesize ")
  if (adjustbox == TRUE){
    top5 <- paste0("\\adjustbox{max width=\\textwidth}{%")
    bottom1 <- paste("\\end{tabular}}")
  }else{
    top5 <- ""
    bottom1 <- paste("\\end{tabular}")
  }
  bottom2 <- paste("\\end{table}")

  # cat out the results - this is essentially just what stargazer does too
  return(cat(top1, top2, top3, top4, top5, paste(output, collapse = "\n"), bottom1, bottom2, sep = "\n"))
}
