#USING R

options(scipen = 999) #tells R to disable scientific notation)
options(pillar.sigfig = 5)

### function to check and install required packages.
### https://stackoverflow.com/a/44660688
Using <- function(...) {
  libs <- unlist(list(...))
  req <- unlist(lapply(libs, require, character.only = TRUE))
  need <- libs[req == FALSE]
  if (length(need) > 0) {
    install.packages(need)
    lapply(need, require, character.only = TRUE)
  }
}

# add all the packages that are used
Using("tidyverse",
      "psych",
      "car",
      "apaTables",
      "emmeans",
      "tidyr",
      "dplyr",
      "readr",
      "effsize",
      "DescTools",
      "broom",
      "xtable",
      "Hmisc",
      "relaimpo",
      "rwa"
)

install.packages("devtools") #Relative Weights Analysis
devtools::install_github("martinctc/rwa") 


# load packages.
source("corstars_function.r")

##########################################

#DATA PROCESS 

#import data
COVID <- read.csv("2022_Supplementary_Data.csv",
                   stringsAsFactors = FALSE,
                   na.strings = c("", "NA")
) 


###########################################

#Multiple Regression. Using scale in the function below mean centers the variables and gives the standardised beta weights.

lm.allpredictors <- lm(scale(RELAT_TOT) ~ scale(ROES_DISTRACT) + scale(ROES_VALUE) + scale(ROES_SOCSHARE) + scale(ROES_REAPP) + scale(ROES_HUMOUR) + scale(ROES_EXPSUPP) + scale(ROES_DOWNCOMP) + scale(ROES_DIRECTACT), data =  COVID)
tidy(lm.allpredictors)
glance(lm.allpredictors)
summary(lm.allpredictors)

effects::partial-residual

#Correlation tables plus new dataframe with just variables for correlation
CovidCors <- COVID %>%
  dplyr::select(ROES_EXPSUPP, ROES_DOWNCOMP, ROES_HUMOUR, ROES_DISTRACT, ROES_DIRECTACT, ROES_REAPP, ROES_SOCSHARE, ROES_VALUE, RELAT_TOT)

  
corstars(CovidCors, result="html")


#*********************** Relative Importance of each variable in the model % R2 ******************************

CovidCors %>%
  rwa(outcome = "RELAT_TOT",
      predictors = c("ROES_EXPSUPP", "ROES_DOWNCOMP", "ROES_HUMOUR", "ROES_DISTRACT", "ROES_DIRECTACT", "ROES_REAPP", "ROES_SOCSHARE", "ROES_VALUE"),
      applysigns = TRUE)

