1 Loading Libraries

#install.packages("afex")
#install.packages("emmeans")
#install.packages("ggbeeswarm")
#install.packages("expss")

library(psych) # for the describe() command
library(ggplot2) # to visualize our results
## 
## Attaching package: 'ggplot2'
## The following objects are masked from 'package:psych':
## 
##     %+%, alpha
library(expss) # for the cross_cases() command
## Loading required package: maditr
## 
## To get total summary skip 'by' argument: take_all(mtcars, mean)
## 
## Use 'expss_output_viewer()' to display tables in the RStudio Viewer.
##  To return to the console output, use 'expss_output_default()'.
## 
## Attaching package: 'expss'
## The following object is masked from 'package:ggplot2':
## 
##     vars
library(car) # for the leveneTest() command
## Loading required package: carData
## 
## 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 
## Loading required package: lme4
## Loading required package: Matrix
## Registered S3 method overwritten by 'lme4':
##   method           from
##   na.action.merMod car
## 
## 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(ggbeeswarm) # to run plot results
library(emmeans) # for posthoc tests
## Welcome to emmeans.
## Caution: You lose important information if you filter this package's results.
## See '? untidy'

2 Importing Data

# For HW, import the project dataset you cleaned previously this will be the dataset you'll use throughout the rest of the semester

d <- read.csv(file="Data/projectdata.csv", header=T)


# new code! this adds a column with a number for each row. It will make it easier if we need to drop outliers later
d$row_id <- 1:nrow(d)

3 State Your Hypothesis

Note: For your HW, you will choose to run EITHER a one-way ANOVA (a single IV with 3 or more levels) OR a two-way/factorial ANOVA (at least two IVs with 2 or 3 levels each). You will need to specify your hypothesis and customize your code based on the choice you make. We will run BOTH versions of the test in the lab for illustrative purposes.

One-Way: We predict that there will be a significant difference in isolation by people’s level of mental health, between anxiety disorder, depression, and eating disorders.

Two-Way: We predict that there will a significant difference in people’s level of felt isolation based on people’s level of mental health (anxiety disorder, depression) and their gender (female, male). We also predict that there will be a significant interraction between mental health and gender.

4 Check Your Variables

# you only need to check the variables you're using in the current analysis

str(d)
## 'data.frame':    716 obs. of  8 variables:
##  $ X          : int  520 2814 3146 3295 717 6056 4753 5365 2044 1965 ...
##  $ gender     : chr  "female" "male" "female" "male" ...
##  $ mhealth    : chr  "none or NA" "none or NA" "none or NA" "none or NA" ...
##  $ covid_pos  : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ covid_neg  : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ isolation_c: num  1 1 1 1 1 1 1 1 1 1 ...
##  $ support    : num  2.83 3 4 4 3.67 ...
##  $ row_id     : int  1 2 3 4 5 6 7 8 9 10 ...
# make our categorical variables of interest "factors"
# because we'll use our newly created row ID variable for this analysis, so make sure it's coded as a factor, too.
d$mhealth <- as.factor(d$mhealth)

# If the IV has more than 2 levels, you must DROP any additional levels in order to meet the first assumption of a t-test.

## NOTE: This is a FOUR STEP process!

d <- subset(d, mhealth  != "ptsd") # use subset() to remove all participants from the additional level

table(d$mhealth, useNA = "always") # verify that now there are ZERO participants in the additional level
## 
##              anxiety disorder                       bipolar 
##                            79                             3 
##                    depression              eating disorders 
##                            13                            20 
##                    none or NA obsessive compulsive disorder 
##                           554                            15 
##                         other                          ptsd 
##                            19                             0 
##                          <NA> 
##                             0
d$mhealth <- droplevels(d$mhealth) # use droplevels() to drop the empty factor

table(d$mhealth, useNA = "always") # verify that now the entire factor level is removed 
## 
##              anxiety disorder                       bipolar 
##                            79                             3 
##                    depression              eating disorders 
##                            13                            20 
##                    none or NA obsessive compulsive disorder 
##                           554                            15 
##                         other                          <NA> 
##                            19                             0
d <- subset(d, mhealth  != "obsessive compulsive disorder") # use subset() to remove all participants from the additional level

table(d$mhealth, useNA = "always") # verify that now there are ZERO participants in the additional level
## 
##              anxiety disorder                       bipolar 
##                            79                             3 
##                    depression              eating disorders 
##                            13                            20 
##                    none or NA obsessive compulsive disorder 
##                           554                             0 
##                         other                          <NA> 
##                            19                             0
d$mhealth <- droplevels(d$mhealth) # use droplevels() to drop the empty factor

table(d$mhealth, useNA = "always") # verify that now the entire factor level is removed 
## 
## anxiety disorder          bipolar       depression eating disorders 
##               79                3               13               20 
##       none or NA            other             <NA> 
##              554               19                0
d <- subset(d, mhealth  != "bipolar") # use subset() to remove all participants from the additional level

table(d$mhealth, useNA = "always") # verify that now there are ZERO participants in the additional level
## 
## anxiety disorder          bipolar       depression eating disorders 
##               79                0               13               20 
##       none or NA            other             <NA> 
##              554               19                0
d$mhealth <- droplevels(d$mhealth) # use droplevels() to drop the empty factor

table(d$mhealth, useNA = "always") # verify that now the entire factor level is removed 
## 
## anxiety disorder       depression eating disorders       none or NA 
##               79               13               20              554 
##            other             <NA> 
##               19                0
d <- subset(d, mhealth  != "none or NA") # use subset() to remove all participants from the additional level

table(d$mhealth, useNA = "always") # verify that now there are ZERO participants in the additional level
## 
## anxiety disorder       depression eating disorders       none or NA 
##               79               13               20                0 
##            other             <NA> 
##               19                0
d$mhealth <- droplevels(d$mhealth) # use droplevels() to drop the empty factor

table(d$mhealth, useNA = "always") # verify that now the entire factor level is removed 
## 
## anxiety disorder       depression eating disorders            other 
##               79               13               20               19 
##             <NA> 
##                0
d <- subset(d, mhealth  != "other") # use subset() to remove all participants from the additional level

table(d$mhealth, useNA = "always") # verify that now there are ZERO participants in the additional level
## 
## anxiety disorder       depression eating disorders            other 
##               79               13               20                0 
##             <NA> 
##                0
d$mhealth <- droplevels(d$mhealth) # use droplevels() to drop the empty factor

table(d$mhealth, useNA = "always") # verify that now the entire factor level is removed 
## 
## anxiety disorder       depression eating disorders             <NA> 
##               79               13               20                0
## Repeat ALL THE STEPS ABOVE if your IV has more levels that need to be DROPPED. Copy the 4 lines of code, and replace the level name in the subset() command.
d$row_id <- as.factor(d$row_id)

# check that all our categorical variables of interest are now factors
str(d)
## 'data.frame':    112 obs. of  8 variables:
##  $ X          : int  1761 3548 6035 2605 2525 7159 5722 2453 3079 779 ...
##  $ gender     : chr  "female" "male" "female" "female" ...
##  $ mhealth    : Factor w/ 3 levels "anxiety disorder",..: 1 1 2 1 1 1 3 1 1 3 ...
##  $ covid_pos  : int  0 0 0 0 0 13 0 0 0 0 ...
##  $ covid_neg  : int  0 0 0 0 0 3 0 0 0 0 ...
##  $ isolation_c: num  1 1 1.25 1.25 1.25 1.25 1.25 1.5 1.5 1.5 ...
##  $ support    : num  4.17 3.83 4.33 4.17 4.67 ...
##  $ row_id     : Factor w/ 112 levels "13","45","70",..: 1 2 3 4 5 6 7 8 9 10 ...
# check our DV skew and kurtosis
describe(d$isolation_c)
##    vars   n mean   sd median trimmed  mad min max range  skew kurtosis   se
## X1    1 112 2.68 0.75      3    2.76 0.74   1 3.5   2.5 -0.58    -0.89 0.07
# we'll use the describeBy() command to view our DV's skew and kurtosis across our IVs' levels
describeBy(d$isolation_c, group = d$mhealth)
## 
##  Descriptive statistics by group 
## group: anxiety disorder
##    vars  n mean   sd median trimmed  mad min max range  skew kurtosis   se
## X1    1 79 2.66 0.76   2.75    2.73 1.11   1 3.5   2.5 -0.56    -0.93 0.09
## ------------------------------------------------------------ 
## group: depression
##    vars  n mean  sd median trimmed  mad  min max range  skew kurtosis   se
## X1    1 13 2.87 0.7      3    2.95 0.74 1.25 3.5  2.25 -0.91    -0.32 0.19
## ------------------------------------------------------------ 
## group: eating disorders
##    vars  n mean   sd median trimmed  mad  min max range  skew kurtosis   se
## X1    1 20 2.64 0.73   2.88    2.69 0.93 1.25 3.5  2.25 -0.38    -1.34 0.16
# also use histograms to examine your continuous variable
hist(d$isolation_c)

# REMEMBER your test's level of POWER is determined by your SMALLEST subsample

5 Check Your Assumptions

5.1 ANOVA Assumptions

  • DV should be normally distributed across levels of the IV (we checked previously using “describeBy” function)
  • All levels of the IVs should have an equal number of cases and there should be no empty cells. Cells with low numbers decrease the power of the test (which increases chance of Type II error)
  • Homogeneity of variance should be confirmed (using Levene’s Test)
  • Outliers should be identified and removed – we will actually remove them this time!
  • If you have confirmed everything above, the sampling distribution should be normal.

5.1.1 Check levels of IVs

# One-Way
table(d$mhealth)
## 
## anxiety disorder       depression eating disorders 
##               79               13               20
## If cross_cases() doesn't work for you, then use xtabs() instead. Fill in the code below and remove the "#" to run. Then hashtag out the cross_cases() line above.

#xtabs(~ V1 + V2, data=d)

### Check homogeneity of variance

6 use the leveneTest() command from the car package to test homogeneity of variance

7 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

8 One-Way

leveneTest(isolation_c~mhealth, data = d)

8.0.1 Check for outliers using Cook’s distance and Residuals VS Leverage plot

8.0.1.1 Run a Regression to get both outlier plots

# use this commented out section below ONLY IF if you need to remove outliers
# to drop a single outlier, use this code:
 d <- subset(d, row_id!=c(1108))

# to drop multiple outliers, use this code:
# d <- subset(d, row_id!=c(1108) & row_id!=c(602))


# use the lm() command to run the regression
# formula is y~x1*x2 + c, where y is our DV, x1 is our first IV, x2 is our second IV.

# One-Way
reg_model <- lm(isolation_c~mhealth, data = d) 

8.0.1.2 Check for outliers (One-Way)

# Cook's distance
plot(reg_model, 4)

# Residuals VS Leverage
plot(reg_model, 5)

8.1 Issues with My Data

Our cell sizes are very unbalanced between the mental health group levels. 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 was significant for our three level mental health variable with the One-Way ANOVA. We are ignoring this and continuing with the analysis anyway for this class.

We identified and removed a single outlier for the One-Way ANOVA.

[UPDATE this section in your HW.]

9 Run an ANOVA

# One-Way
aov_model <- aov_ez(data = d,
                    id = "X",
                    between = c("mhealth"),
                    dv = "isolation_c",
                    anova_table = list(es = "pes"))
## Contrasts set to contr.sum for the following variables: mhealth

10 View Output

# One-Way
nice(aov_model)
## Anova Table (Type 3 tests)
## 
## Response: isolation_c
##    Effect     df  MSE    F  pes p.value
## 1 mhealth 2, 109 0.56 0.44 .008    .643
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '+' 0.1 ' ' 1

ANOVA Effect Size [partial eta-squared] cutoffs from Cohen (1988): * η^2 < 0.01 indicates a trivial effect * η^2 >= 0.01 indicates a small effect * η^2 >= 0.06 indicates a medium effect * η^2 >= 0.14 indicates a large effect

11 Visualize Results

# One-Way
afex_plot(aov_model, x = "mhealth")

12 Run Posthoc Tests (One-Way)

ONLY run posthoc IF the ANOVA test is SIGNIFICANT! E.g., only run the posthoc tests on mental health type if there is a main effect for mental health type

emmeans(aov_model, specs="mhealth", adjust="sidak")
##  mhealth          emmean     SE  df lower.CL upper.CL
##  anxiety disorder   2.66 0.0845 109     2.46     2.87
##  depression         2.87 0.2080 109     2.36     3.37
##  eating disorders   2.64 0.1680 109     2.23     3.04
## 
## Confidence level used: 0.95 
## Conf-level adjustment: sidak method for 3 estimates
pairs(emmeans(aov_model, specs="mhealth", adjust="sidak"))
##  contrast                            estimate    SE  df t.ratio p.value
##  anxiety disorder - depression        -0.2008 0.225 109  -0.893  0.6457
##  anxiety disorder - eating disorders   0.0271 0.188 109   0.144  0.9886
##  depression - eating disorders         0.2279 0.268 109   0.852  0.6718
## 
## P value adjustment: tukey method for comparing a family of 3 estimates

13 Write Up Results

13.1 One-Way ANOVA

To test our hypothesis that there will be a significant difference in people’s level of felt isolation based on their mental health (anxiety, depression, eating disorders), we used a one-way ANOVA. Our data was unbalanced, with many more people who had an anxiety disorder participating in our survey (n = 79) than those with depression (n = 13) or an eating disorder (20). This significantly reduces the power of our test and increases the chances of a Type II error. A significant Levene’s test (p = .13) 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(7, 708) = 8.83, p <.001, ηp2 = .080 (medium effect size; Cohen, 1988). Posthoc tests using Tukey’s adjustment revealed that participants who have depression (M = 2.87, SE = .19) reported more isolation than those with anxiety disorders (M = 2.66, SE = .09) but less isolation than those with eating disorders (M = 2.64, SE = .16); levels of isolation differed across mental health conditions we examined, with depression being the associated with higher level of isolation in participants overall (see Figure 1 for a comparison).

References

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