1 Loading Libraries

library(psych) # for the describe() command
library(ggplot2) # to visualize our results
## Warning: package 'ggplot2' was built under R version 4.3.3
## 
## Attaching package: 'ggplot2'
## The following objects are masked from 'package:psych':
## 
##     %+%, alpha
library(expss) # for the cross_cases() command
## Loading required package: maditr
## 
## To aggregate data: take(mtcars, mean_mpg = mean(mpg), by = am)
## 
## Attaching package: 'expss'
## The following object is masked from 'package:ggplot2':
## 
##     vars
library(car) # for the leveneTest() command
## Warning: package 'car' was built under R version 4.3.3
## Loading required package: carData
## Warning: package 'carData' was built under R version 4.3.3
## 
## Attaching package: 'car'
## The following object is masked from 'package:expss':
## 
##     recode
## The following object is masked from 'package:psych':
## 
##     logit
library(afex) # to run the ANOVA and plot results
## Warning: package 'afex' was built under R version 4.3.3
## Loading required package: lme4
## Warning: package 'lme4' was built under R version 4.3.3
## Loading required package: Matrix
## 
## Attaching package: 'lme4'
## The following object is masked from 'package:expss':
## 
##     dummy
## ************
## Welcome to afex. For support visit: http://afex.singmann.science/
## - Functions for ANOVAs: aov_car(), aov_ez(), and aov_4()
## - Methods for calculating p-values with mixed(): 'S', 'KR', 'LRT', and 'PB'
## - 'afex_aov' and 'mixed' objects can be passed to emmeans() for follow-up tests
## - Get and set global package options with: afex_options()
## - Set sum-to-zero contrasts globally: set_sum_contrasts()
## - For example analyses see: browseVignettes("afex")
## ************
## 
## Attaching package: 'afex'
## The following object is masked from 'package:lme4':
## 
##     lmer
library(emmeans) # for posthoc tests
## Warning: package 'emmeans' was built under R version 4.3.3

2 Importing Data

# import the dataset you cleaned previously
# this will be the dataset you'll use throughout the rest of the semester
# use ARC data
d <- read.csv(file="data/mydata.csv", header=T)

# for the HW, you may or may not need to use the code below this comment
# check to see if you have a variable called 'X' or 'ResponseId' in your data
names(d)
## [1] "X"         "age"       "mhealth"   "pas_covid" "phq"       "gad"      
## [7] "swemws"
# if you do have 'X' or 'ResponseId' (aka your ID variable) then DELETE THE CODE BELOW
# if you don't have those variables, keep the code and run it
d$row_id <- 1:nrow(d)

3 State Your Hypothesis

Note: You can chose to run either a one-way ANOVA (a single IV with more than 3 levels) or a two-way/factorial ANOVA (at least two IVs) for the homework. You will need to specify your hypothesis and customize your code based on the choice you make. I will run both versions of the test here for illustrative purposes.

One-Way: We predict that mental health will have a significant effect on well-being, as measured by the Short Warwick-Edinburgh Mental Well-being Scale (swemws).

4 Check Your Variables

# you only need to check the variables you're using in the current analysis
# although you checked them previously, it's always a good idea to look them over again and be sure that everything is correct
str(d)
## 'data.frame':    912 obs. of  8 variables:
##  $ X        : int  20 30 31 33 57 58 81 104 113 117 ...
##  $ age      : chr  "1 under 18" "1 under 18" "4 between 36 and 45" "4 between 36 and 45" ...
##  $ mhealth  : chr  "anxiety disorder" "none or NA" "none or NA" "none or NA" ...
##  $ pas_covid: num  4.56 3.33 4.22 3.22 4.56 ...
##  $ phq      : num  3.33 1 2.33 1.11 2.33 ...
##  $ gad      : num  3.86 1.14 2 1.43 2.86 ...
##  $ swemws   : num  2.29 4.29 3.29 4 3.29 ...
##  $ row_id   : int  1 2 3 4 5 6 7 8 9 10 ...
# make our categorical variables factors
d$row_id <- as.factor(d$row_id) #we'll actually use our ID variable for this analysis, so make sure it's coded as a factor
d$mhealth <- as.factor(d$mhealth)

# check your categorical variables
table(d$mhealth)
## 
##              anxiety disorder                       bipolar 
##                            94                             3 
##                    depression              eating disorders 
##                            23                            17 
##                    none or NA obsessive compulsive disorder 
##                           724                            14 
##                         other                          ptsd 
##                            23                            14
# also use histograms to examine your continuous variable
hist(d$swemws)

5 Check Your Assumptions

5.1 ANOVA Assumptions

Assumptions checked below:

  • DV should be normally distributed across levels of the IV
  • All levels of the IVs should have equal number of cases and there should be no empty cells. Cells with low numbers decrease the power of the test (increase change of Type II error)
  • Homogeneity of variance should be assured
  • Outliers should be identified and removed

If you have confirmed everything else…

  • The sampling distribution should be normal. (For a demonstration of what the sampling distribution is, go here.)

5.1.1 Check levels of IVs

# check your categorical variables and make sure they have decent cell sizes
# they should have at least 5 participants in each cell
# but larger numbers are always better
table(d$mhealth)
## 
##              anxiety disorder                       bipolar 
##                            94                             3 
##                    depression              eating disorders 
##                            23                            17 
##                    none or NA obsessive compulsive disorder 
##                           724                            14 
##                         other                          ptsd 
##                            23                            14
# we're going to recode our race/ethnicity variable into two groups: poc and white
# you may or may not need to combine and/or drop groups for the HW
#pay attention to the name of your variable and levels of your variable for HW, when you recode you have to enter the exact label that is used for that level of the variable (for ex: upper case A would not work for asian)
d$mhealth2[d$mhealth == "anxiety disorder"] <- "mood"
d$mhealth2[d$mhealth == "bipolar"] <- "mood"
d$mhealth2[d$mhealth == "depression"] <- "mood"
d$mhealth2[d$mhealth == "eating disorders"] <- "other"
d$mhealth2[d$mhealth == "none or NA"] <- "none"
d$mhealth2[d$mhealth == "obsessive compulsive disorder"] <- "other"
d$mhealth2[d$mhealth == "other"] <- "other"
d$mhealth2[d$mhealth == "ptsd"] <- "other"
table(d$mhealth2, useNA = "always")
## 
##  mood  none other  <NA> 
##   120   724    68     0
d$mhealth2 <- as.factor(d$mhealth2)

# our number of small nb participants is going to hurt us for the two-way anova, but it should be okay for the one-way anova
# so we'll create a new dataframe for the two-way analysis and call it d2

# to double-check any changes we made

# you can use the describe() command on an entire dataframe (d) or just on a single variable
describe(d$swemws)
##    vars   n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 912 3.18 0.83   3.29     3.2 0.85   1   5     4 -0.2    -0.36 0.03
# we'll use the describeBy() command to view skew and kurtosis across our IVs
describeBy(d$swemws, group = d$mhealth2)
## 
##  Descriptive statistics by group 
## group: mood
##    vars   n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 120 2.82 0.85   2.71    2.82 0.85   1   5     4 0.17     -0.2 0.08
## ------------------------------------------------------------ 
## group: none
##    vars   n mean  sd median trimmed  mad min max range skew kurtosis   se
## X1    1 724  3.3 0.8   3.43    3.32 0.85   1   5     4 -0.3     -0.2 0.03
## ------------------------------------------------------------ 
## group: other
##    vars  n mean   sd median trimmed  mad  min  max range skew kurtosis   se
## X1    1 68 2.62 0.77   2.57    2.59 0.85 1.29 4.86  3.57 0.39    -0.12 0.09

5.1.2 Check homogeneity of variance

# use the leveneTest() command from the car package to test homogeneity of variance
# uses the 'formula' setup: formula is y~x1*x2, where y is our DV and x1 is our first IV and x2 is our second IV
leveneTest(swemws~mhealth2, data = d)
## Levene's Test for Homogeneity of Variance (center = median)
##        Df F value Pr(>F)
## group   2  0.3986 0.6714
##       909
#leveneTest(pss~gender_rc*poc, data = d2)

5.1.3 Check for outliers using Cook’s distance and Residuals vs Leverage plot

5.1.3.1 Run a Regression

# use the lm() command to run the regression
# formula is y~x1*x2, where y is our DV, x1 is our first IV and x2 is our second IV
reg_model <- lm(swemws~mhealth2, data = d) #for one-way
#reg_model2 <- lm(pss~gender_rc*poc, data = d2) #for two-way

5.1.3.2 Check for outliers (One-Way)

# Cook's distance
plot(reg_model, 4)

# Residuals vs Leverage
plot(reg_model, 5)

5.1.3.3 Check for outliers (Two-Way)

# Cook's distance
#plot(reg_model2, 4)

# Residuals vs Leverage
#plot(reg_model2, 5)

5.2 Issues with My Data

Our cell sizes are very unbalanced. A small sample size for one of the levels of our variable limits our power and increases our Type II error rate.

Levene’s test is not significant for our three-level mental health variable.

We did not identify any outliers.

6 Run an ANOVA

aov_model <- aov_ez(data = d,
                    id = "row_id",
                    between = c("mhealth2"),
                    dv = "swemws",
                    anova_table = list(es = "pes"))
## Contrasts set to contr.sum for the following variables: mhealth2

7 View Output

Effect size cutoffs from Cohen (1988):

  • η2 = 0.01 indicates a small effect
  • η2 = 0.06 indicates a medium effect
  • η2 = 0.14 indicates a large effect
nice(aov_model)
## Anova Table (Type 3 tests)
## 
## Response: swemws
##     Effect     df  MSE         F  pes p.value
## 1 mhealth2 2, 909 0.65 36.53 *** .074   <.001
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '+' 0.1 ' ' 1
#nice(aov_model2)

8 Visualize Results

afex_plot(aov_model, x = "mhealth2")

#afex_plot(aov_model2, x = "gender_rc", trace = "poc")
#afex_plot(aov_model2, x = "poc", trace = "gender_rc")

9 Run Posthoc Tests (One-Way)

Only run posthocs if the test is significant! E.g., only run the posthoc tests on gender if there is a main effect for gender.

emmeans(aov_model, specs="mhealth2", adjust="tukey")
## Note: adjust = "tukey" was changed to "sidak"
## because "tukey" is only appropriate for one set of pairwise comparisons
##  mhealth2 emmean     SE  df lower.CL upper.CL
##  mood       2.82 0.0734 909     2.65     3.00
##  none       3.30 0.0299 909     3.23     3.37
##  other      2.62 0.0975 909     2.38     2.85
## 
## Confidence level used: 0.95 
## Conf-level adjustment: sidak method for 3 estimates
pairs(emmeans(aov_model, specs="mhealth2", adjust="tukey"))
##  contrast     estimate     SE  df t.ratio p.value
##  mood - none    -0.477 0.0792 909  -6.019  <.0001
##  mood - other    0.206 0.1220 909   1.688  0.2104
##  none - other    0.683 0.1019 909   6.697  <.0001
## 
## P value adjustment: tukey method for comparing a family of 3 estimates

10 Run Posthoc Tests (Two-Way)

Only run posthocs if the test is significant! E.g., only run the posthoc tests on gender if there is a main effect for gender.

#emmeans(aov_model2, specs="gender_rc", adjust="tukey")
#pairs(emmeans(aov_model2, specs="gender_rc", adjust="tukey"))
 
#emmeans(aov_model2, specs="poc", adjust="tukey")
#pairs(emmeans(aov_model2, specs="poc", adjust="tukey"))
 
#emmeans(aov_model2, specs="gender_rc", by="poc", adjust="sidak")
#pairs(emmeans(aov_model2, specs="gender_rc", by="poc", adjust="sidak"))

#emmeans(aov_model2, specs="poc", by="gender_rc", adjust="sidak")
#pairs(emmeans(aov_model2, specs="poc", by="gender_rc", adjust="sidak"))

11 Write Up Results

11.1 One-Way ANOVA

To test our hypothesis that mental health would have a significant effect on well-being, we used a one-way ANOVA. Our data was unbalanced, with many more individuals with no mental health disorders in our survey (n = 724 ) than individuals with anxiety disorder (n = 94), bipolar (n = 3), depression (n = 23), eating disorders(n = 17), obsessive compulsive disorder(n = 14), ptsd(n = 14), or other(n = 23). This significantly reduces the power of our test and increases the chances of a Type II error. We did not identify any outliers following visual analysis of a Residuals vs Leverage plot. A significant Levene’s test (p = .002 ) also indicates that our data violates the assumption of homogeneity of variance.This suggests that there is an increased chance of Type I error. We continued with our analysis for the purpose of this class.

We found a significant effect of mental health, F(2,909) = 36.53, p < .001, ηp2 = .074 (large effect size; Cohen, 1988). Posthoc tests using Tukey’s HSD revealed that individuals with no mental health disorders reported better well-being than individuals with mood disorders and other mental health disorders. (see Figure 1 for a comparison).

11.2 Two-Way ANOVA

References

Cohen J. (1988). Statistical Power Analysis for the Behavioral Sciences. New York, NY: Routledge Academic.