##
## Final preparations for data analysis
##

rm(list=ls(all=TRUE))

## Change working directory accordingly!
setwd("../")

##
## Load necessary R packages
##
# Packages and functions for ordinal regression analysis
# - rms: orm()
# - ordinal: clm()
# - MASS: polr()
library(ordinal)
library(dataframes2xls)
library(plyr)
library(dplyr)
library(reshape2)
library(ggplot2)
source("Visualization_Theme.R")

# package rms required for
#  - vif()
#  - calculates also Nagelkerke's pseudo R^2 und Chi^2-Statistic
library(rms)

# helper functions for exporting relevant model parameters to an Excel file
# export.param <- function(x){
#    coeffs <- summary(x)$coefficients
#    oratios <- exp(x$coefficients)
#    vifs <- vif(x) # require("rms")
#    tab <- cbind(coeffs, oratios, vifs)
#    #write.xlsx(tmp, "Daten/tmp.xlsx")
#    write.xls(coeffs, "Daten/tmp.xls", col.names = T, row.names = T)    
#    rm(tab, coeffs, oratios, vifs)
#  }

# function for combining coeffs with other important params
# combine.param <- function(x){
#   coeffs <- summary(x)$coefficients
#   oratios <- exp(x$coefficients)
#   vifs <- vif(x) # require("rms")
#   tmp <- cbind(coeffs, oratios, vifs)
#   return(tmp)
#   rm(tmp, coeffs, oratios, vifs)
# }

# use rms package to extract nagelkerke pseudo-R
nagelkerke <- function(model.formula, model.data){
  require(rms)
  tmp.model <- orm(formula = model.formula, data = model.data)
  nR2 <- tmp.model$stats["R2"]     # Nagelkerke Pseudo-R
  return(nR2)
}

## Load Data Set
load("Analyses/Data - States.RData")

# only active conflicts, not interim or post-conflict years
states.active <- subset(states, subset = conflictyear == 1 & !is.na(max_prev) )

# options needed for rms to work properly
dd <- datadist(states.active)
options(datadist='dd')
