Attachment 'quick_chi_squareds.R'
Download 1 library(ggplot2)
2 library(dplyr)
3 library(purrr)
4
5 # Compares glmer models of various nuisance factors to a null model to get their chi-squareds
6 make_chi_squareds_df<-function(df,
7 nuisance_factors, #Needs to be a vector of column name strings
8 formula_prefix_string, # E.g.: "BinaryCorrect ~ 1"
9 fixed_effects_string # E.g.: "(1 | WorkerId) + (1 | Word)"
10 ) {
11 #Gets rid of any NAs
12 df<-df[complete.cases(df[, nuisance_factors]),]
13 #Refactors everything
14 df<-as.data.frame(lapply(df, function (x) if (is.factor(x)) factor(x) else x))
15 #Makes the null model
16 null_model <- glmer(as.formula(paste0(formula_prefix_string, " + ", fixed_effects_string)),
17 data=df, family = "binomial")
18 #Defines A function that makes the nuisance factor models in 'map'
19 glmer_nuisance_modeler<- function(nuisance_factor) {
20 m <- glmer(formula =
21 as.formula(paste0(
22 formula_prefix_string, " + ", nuisance_factor, " + ",
23 fixed_effects_string)),
24 data=df,
25 family="binomial")
26 return(m)
27 }
28 # Gets the Chi-squareds
29 chisqs <- nuisance_factors %>%
30 map(~glmer_nuisance_modeler(.)) %>%
31 map(~anova(.,null_model)) %>%
32 map_dbl(~.$Chisq[2])
33
34 chisq_df <- data.frame(
35 names=as.character(nuisance_factors),
36 chi_squareds = chisqs)
37
38 return(chisq_df)
39 }
40
41 # Quick example.
42 iris$Sepal.Length.Binary<-ifelse(iris$Sepal.Length > 5,1,0)
43 make_chi_squareds_df(iris,
44 c("Petal.Width","Sepal.Width","Petal.Length"),
45 "Sepal.Length.Binary ~ 1",
46 "(1 | Species)") %>%
47 ggplot(aes(x=names,y=chi_squareds,fill=names)) +
48 geom_bar(stat="identity") +
49 theme(axis.text.x=element_blank())
Attached Files
To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.You are not allowed to attach a file to this page.