library(ggplot2)
library(dplyr)
library(purrr)

# Compares glmer models of various nuisance factors to a null model to get their chi-squareds
make_chi_squareds_df<-function(df,
                               nuisance_factors, #Needs to be a vector of column name strings
                               formula_prefix_string, # E.g.: "BinaryCorrect ~ 1"
                               fixed_effects_string # E.g.: "(1 | WorkerId) + (1 | Word)"
) {
  #Gets rid of any NAs
  df<-df[complete.cases(df[, nuisance_factors]),]
  #Refactors everything
  df<-as.data.frame(lapply(df, function (x) if (is.factor(x)) factor(x) else x))
  #Makes the null model
  null_model <- glmer(as.formula(paste0(formula_prefix_string, " + ", fixed_effects_string)),
                      data=df, family = "binomial")
  #Defines A function that makes the nuisance factor models in 'map'
  glmer_nuisance_modeler<- function(nuisance_factor) {
    m <- glmer(formula =
                 as.formula(paste0(
                   formula_prefix_string, " + ", nuisance_factor, " + ",
                   fixed_effects_string)),
               data=df,
               family="binomial")
    return(m)
  }
  # Gets the Chi-squareds
  chisqs <- nuisance_factors %>%
    map(~glmer_nuisance_modeler(.)) %>%
    map(~anova(.,null_model)) %>%
    map_dbl(~.$Chisq[2])

  chisq_df <- data.frame(
    names=as.character(nuisance_factors),
    chi_squareds = chisqs)

  return(chisq_df)
}

# Quick example.
iris$Sepal.Length.Binary<-ifelse(iris$Sepal.Length > 5,1,0)
make_chi_squareds_df(iris,
                     c("Petal.Width","Sepal.Width","Petal.Length"),
                     "Sepal.Length.Binary ~ 1",
                     "(1 | Species)") %>%
  ggplot(aes(x=names,y=chi_squareds,fill=names)) +
  geom_bar(stat="identity") +
  theme(axis.text.x=element_blank())
