1 Loading Libraries

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

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 drop variable use NULL: let(mtcars, am = NULL) %>% head()
## 
## Use 'expss_output_rnotebook()' to display tables inside R Notebooks.
##  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
## 
## 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: There will be a significant difference in maturity level by disability status.

4 Check Your Variables

# you only need to check the variables you're using in the current analysis
# even if 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':    854 obs. of  8 variables:
##  $ ResponseID  : chr  "R_12G7bIqN2wB2N65" "R_3lLnoV2mYVYHFvf" "R_1gTNDGWsqikPuEX" "R_3G1XvswZmPZTkMU" ...
##  $ gender      : chr  "m" "f" "f" "f" ...
##  $ disability  : chr  "psychiatric" "other" "learning" "psychiatric" ...
##  $ mindful     : num  2.2 1.6 1.8 4.27 3.4 ...
##  $ socmeduse   : int  34 37 26 23 35 30 40 34 38 42 ...
##  $ efficacy    : num  2.2 3.1 2.9 3.1 2.8 2.9 3.3 1.9 2.7 3 ...
##  $ moa_maturity: num  3.67 2 4 3.67 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$disability <- as.factor(d$disability) 
d$row_id <- as.factor(d$row_id)

# we're going to recode our race variable into two groups: poc and white
# in doing so, we are creating a new variable "poc" that has 2 levels
table(d$disability)
## 
## chronic health       learning          other       physical    psychiatric 
##            146            121             87             50            380 
##        sensory 
##             70
 d<- subset(d, disability != "physical") # use subset() to remove all participants from the additional level

table(d$disability, useNA = "always") # verify that now there are ZERO participants in the additional level d$gender<- droplevels(d$gender) # use droplevels() to drop the empty factor
## 
## chronic health       learning          other       physical    psychiatric 
##            146            121             87              0            380 
##        sensory           <NA> 
##             70              0
d$disability<- droplevels(d$disability) # use droplevels() to drop the empty factor

table(d$disability, useNA = "always") # verify that now the entire factor level is removed 
## 
## chronic health       learning          other    psychiatric        sensory 
##            146            121             87            380             70 
##           <NA> 
##              0
d<- subset(d, disability != "other") # use subset() to remove all participants from the additional level

table(d$disability, useNA = "always") # verify that now there are ZERO participants in the additional level d$gender<- droplevels(d$gender) # use droplevels() to drop the empty factor
## 
## chronic health       learning          other    psychiatric        sensory 
##            146            121              0            380             70 
##           <NA> 
##              0
d$disability<- droplevels(d$disability) # use droplevels() to drop the empty factor

table(d$disability, useNA = "always") # verify that now the entire factor level is removed 
## 
## chronic health       learning    psychiatric        sensory           <NA> 
##            146            121            380             70              0
d<- subset(d, disability != "sensory") # use subset() to remove all participants from the additional level

table(d$disability, useNA = "always") # verify that now there are ZERO participants in the additional level d$gender<- droplevels(d$gender) # use droplevels() to drop the empty factor
## 
## chronic health       learning    psychiatric        sensory           <NA> 
##            146            121            380              0              0
d$disability<- droplevels(d$disability) # use droplevels() to drop the empty factor

table(d$disability, useNA = "always") # verify that now the entire factor level is removed 
## 
## chronic health       learning    psychiatric           <NA> 
##            146            121            380              0
#d$poc[d$race == "asian"] <- "poc"
#d$poc[d$race == "black"] <- "poc"
#d$poc[d$race == "mideast"] <- "poc"
#d$poc[d$race == "multiracial"] <- "poc"
#d$poc[d$race == "other"] <- "poc"
#d$poc[d$race == "prefer_not"] <- NA
#d$poc[d$race == "white"] <- "white"

table(d$disability)
## 
## chronic health       learning    psychiatric 
##            146            121            380
d$disability <- as.factor(d$disability)

# check that all our categorical variables of interest are now factors
str(d)
## 'data.frame':    647 obs. of  8 variables:
##  $ ResponseID  : chr  "R_12G7bIqN2wB2N65" "R_1gTNDGWsqikPuEX" "R_3G1XvswZmPZTkMU" "R_2QLjdu3yoxqQ21c" ...
##  $ gender      : chr  "m" "f" "f" "f" ...
##  $ disability  : Factor w/ 3 levels "chronic health",..: 3 2 3 3 3 1 2 1 2 3 ...
##  $ mindful     : num  2.2 1.8 4.27 3.4 3.8 ...
##  $ socmeduse   : int  34 26 23 35 34 38 42 29 21 35 ...
##  $ efficacy    : num  2.2 2.9 3.1 2.8 1.9 2.7 3 3.3 3.3 3.5 ...
##  $ moa_maturity: num  3.67 4 3.67 3.67 4 ...
##  $ row_id      : Factor w/ 854 levels "1","2","3","4",..: 1 3 4 5 8 9 10 11 12 13 ...
# check our DV skew and kurtosis
describe(d$moa_maturity)
##    vars   n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 647 3.58 0.41   3.67    3.63 0.49   2   4     2 -0.9     0.38 0.02
# we'll use the describeBy() command to view our DV's skew and kurtosis across our IVs' levels
describeBy(d$moa_maturity, group = d$disability)
## 
##  Descriptive statistics by group 
## group: chronic health
##    vars   n mean   sd median trimmed  mad  min max range  skew kurtosis   se
## X1    1 146 3.65 0.34   3.67    3.69 0.49 2.33   4  1.67 -0.93     0.82 0.03
## ------------------------------------------------------------ 
## group: learning
##    vars   n mean   sd median trimmed  mad  min max range  skew kurtosis   se
## X1    1 121 3.59 0.44   3.67    3.66 0.49 2.33   4  1.67 -1.01      0.3 0.04
## ------------------------------------------------------------ 
## group: psychiatric
##    vars   n mean   sd median trimmed  mad min max range  skew kurtosis   se
## X1    1 380 3.55 0.42   3.67    3.59 0.49   2   4     2 -0.79     0.13 0.02
# also use histograms to examine your continuous variable
hist(d$moa_maturity)

# and cross_cases() to examine your categorical variables' cell count
cross_cases(d, disability)
 #Total 
 disability 
   chronic health  146
   learning  121
   psychiatric  380
   #Total cases  647
# 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 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 assured (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$disability)
## 
## chronic health       learning    psychiatric 
##            146            121            380
### 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

# One-Way
leveneTest(moa_maturity~disability, data = d)
## Levene's Test for Homogeneity of Variance (center = median)
##        Df F value  Pr(>F)  
## group   2   4.528 0.01115 *
##       644                  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

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

5.1.2.1 Run a Regression to get these outlier plots

# use this commented out section below ONLY IF if you need to remove outliers
# to drop a single outlier, use this code:


# 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.
reg_model12 <- lm(moa_maturity~disability, data = d) 
reg_model <- lm(moa_maturity~disability, data = d) 
#for One-Way

5.1.2.2 Check for outliers (One-Way)

# Cook's distance
plot(reg_model, 4)

# Residuals VS Leverage
plot(reg_model, 5)


## Issues with My Data

Our cell sizes are balanced between the disability type group levels. 

Levene’s test was significant for our three-level pet type variable with the One-Way ANOVA. 

We identified and removed no outliers for the One-Way ANOVA.

[UPDATE this section in your HW.]

# Run an ANOVA


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

6 View Output

nice(aov_model)
## Anova Table (Type 3 tests)
## 
## Response: moa_maturity
##       Effect     df  MSE      F  pes p.value
## 1 disability 2, 644 0.17 3.28 * .010    .038
## ---
## 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

7 Visualize Results

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

# NOTE: for the Two-Way, you will need to decide which plot version makes the MOST SENSE based on your data / rationale when you make the nice Figure 2 at the end

8 Run Posthoc Tests (One-Way)

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

emmeans(aov_model, specs="disability", adjust="sidak")
##  disability     emmean     SE  df lower.CL upper.CL
##  chronic health   3.65 0.0338 644     3.57     3.73
##  learning         3.59 0.0372 644     3.50     3.68
##  psychiatric      3.55 0.0210 644     3.50     3.60
## 
## Confidence level used: 0.95 
## Conf-level adjustment: sidak method for 3 estimates
pairs(emmeans(aov_model, specs="disability", adjust="sidak"))
##  contrast                     estimate     SE  df t.ratio p.value
##  chronic health - learning      0.0589 0.0503 644   1.172  0.4707
##  chronic health - psychiatric   0.1010 0.0398 644   2.538  0.0305
##  learning - psychiatric         0.0422 0.0427 644   0.988  0.5846
## 
## P value adjustment: tukey method for comparing a family of 3 estimates

9 Run Posthoc Tests (Two-Way)

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

# IV1 main effect
emmeans(aov_model, specs="disability", adjust="sidak")
##  disability     emmean     SE  df lower.CL upper.CL
##  chronic health   3.65 0.0338 644     3.57     3.73
##  learning         3.59 0.0372 644     3.50     3.68
##  psychiatric      3.55 0.0210 644     3.50     3.60
## 
## Confidence level used: 0.95 
## Conf-level adjustment: sidak method for 3 estimates
pairs(emmeans(aov_model, specs="disability", adjust="sidak"))
##  contrast                     estimate     SE  df t.ratio p.value
##  chronic health - learning      0.0589 0.0503 644   1.172  0.4707
##  chronic health - psychiatric   0.1010 0.0398 644   2.538  0.0305
##  learning - psychiatric         0.0422 0.0427 644   0.988  0.5846
## 
## P value adjustment: tukey method for comparing a family of 3 estimates

10 Write Up Results

10.1 One-Way ANOVA

To test our hypothesis that there would be a significant effect of disability status on people’s maturity, we used a one-way ANOVA. Our data was unbalanced,Our data was unbalanced, with many more people in the chronic health group participating in our survey (n = 444) than in the learning (n = 136) or psychiatric (n = 67) groups.This significantly reduces the power of our test and increases the chances of a Type II error. We also identified and removed no outliers following visual analysis of Cook’s Distance and Residuals VS Leverage plots. A significant Levene’s test (p = .011) indicates that our data violates the assumption of homogeneity of variance. This suggests an increased chance of Type I error. We continued with our analysis for the purpose of this class.

We found a significant effect of disability status, F(2, 1246) = 27.54, p < .001, ηp² = .042 (large effect size; Cohen, 1988). Post hoc tests using Sidak’s adjustment revealed that participants with a chronic health disability (M = 2.97, SE = .03) reported more maturity than those with a learning disability (M = 2.06, SE = .07) but less maturity than those with a psychiatric disability (M = 3.79, SE = .16); participants with a psychiatric disability reported the highest level of maturity overall (see Figure 1 for a comparison).

```

References

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