1 Loading Libraries

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

library(psych) # for the describe() command
## Warning: package 'psych' was built under R version 4.4.3
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
## Warning: package 'expss' was built under R version 4.4.3
## Loading required package: maditr
## Warning: package 'maditr' was built under R version 4.4.3
## 
## To select rows from data: rows(mtcars, am==0)
## 
## 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
## Warning: package 'car' was built under R version 4.4.3
## Loading required package: carData
## Warning: package 'carData' was built under R version 4.4.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 
## Warning: package 'afex' was built under R version 4.4.3
## Loading required package: lme4
## Warning: package 'lme4' was built under R version 4.4.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(ggbeeswarm) # to run plot results
## Warning: package 'ggbeeswarm' was built under R version 4.4.3
library(emmeans) # for posthoc tests
## Warning: package 'emmeans' was built under R version 4.4.3
## 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 is a significant difference in the means of the sense of belonging across groups of males (m), females (f), and nonbinary (nb) participants.

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':    2163 obs. of  8 variables:
##  $ ResponseID: chr  "R_BJN3bQqi1zUMid3" "R_2TGbiBXmAtxywsD" "R_12G7bIqN2wB2N65" "R_39pldNoon8CePfP" ...
##  $ gender    : chr  "f" "m" "m" "f" ...
##  $ age       : chr  "1 between 18 and 25" "1 between 18 and 25" "1 between 18 and 25" "1 between 18 and 25" ...
##  $ belong    : num  2.8 4.2 3.6 4 3.4 4.2 3.9 3.6 2.9 2.5 ...
##  $ stress    : num  3.3 3.3 4 3.2 3.1 3.5 3.3 2.4 2.9 2.7 ...
##  $ support   : num  6 6.75 5.17 5.58 6 ...
##  $ swb       : num  4.33 4.17 1.83 5.17 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$gender <- as.factor(d$gender) 

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$gender)
## 
##    f    m   nb 
## 1585  547   31
# check that all our categorical variables of interest are now factors
str(d)
## 'data.frame':    2163 obs. of  8 variables:
##  $ ResponseID: chr  "R_BJN3bQqi1zUMid3" "R_2TGbiBXmAtxywsD" "R_12G7bIqN2wB2N65" "R_39pldNoon8CePfP" ...
##  $ gender    : Factor w/ 3 levels "f","m","nb": 1 2 2 1 2 1 1 1 1 1 ...
##  $ age       : chr  "1 between 18 and 25" "1 between 18 and 25" "1 between 18 and 25" "1 between 18 and 25" ...
##  $ belong    : num  2.8 4.2 3.6 4 3.4 4.2 3.9 3.6 2.9 2.5 ...
##  $ stress    : num  3.3 3.3 4 3.2 3.1 3.5 3.3 2.4 2.9 2.7 ...
##  $ support   : num  6 6.75 5.17 5.58 6 ...
##  $ swb       : num  4.33 4.17 1.83 5.17 3.67 ...
##  $ row_id    : Factor w/ 2163 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
# check our DV skew and kurtosis
describe(d$belong)
##    vars    n mean   sd median trimmed  mad min max range  skew kurtosis   se
## X1    1 2163 3.21 0.61    3.2    3.23 0.59 1.3   5   3.7 -0.27    -0.09 0.01
# we'll use the describeBy() command to view our DV's skew and kurtosis across our IVs' levels
describeBy(d$belong, group = d$gender)
## 
##  Descriptive statistics by group 
## group: f
##    vars    n mean   sd median trimmed  mad min max range  skew kurtosis   se
## X1    1 1585 3.26 0.59    3.3    3.27 0.59 1.3   5   3.7 -0.25     -0.2 0.01
## ------------------------------------------------------------ 
## group: m
##    vars   n mean   sd median trimmed  mad min max range  skew kurtosis   se
## X1    1 547 3.06 0.64    3.1    3.08 0.59 1.3 4.9   3.6 -0.22    -0.04 0.03
## ------------------------------------------------------------ 
## group: nb
##    vars  n mean  sd median trimmed  mad min max range skew kurtosis   se
## X1    1 31 3.34 0.5    3.3    3.33 0.44 2.3 4.6   2.3 0.29    -0.09 0.09
# also use histograms to examine your continuous variable
hist(d$belong)

# and cross_cases() to examine your categorical variables' cell count
cross_cases(d, gender)
 #Total 
 gender 
   f  1585
   m  547
   nb  31
   #Total cases  2163
# 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$gender)
## 
##    f    m   nb 
## 1585  547   31
# our small number of participants owning rabbits is going to hurt us for the two-way anova, but it should be okay for the one-way anova
# We will create a new dataframe for the two-way analysis and call it d_twoway and remove the pet owning Ps.

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

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

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

5.1.3.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_model <- lm(belong~gender, data = d) #for One-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.2 Issues with My Data

Our cell sizes are very unbalanced between the gender group levels. A small 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 gender identity variable with the One-way ANOVA. We are ignoring this and continuing with the analysis anyway for this class.

We identified that there are no outliers for our One-Way ANOVA.

[UPDATE this section in your HW.]

6 Run an ANOVA

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

7 View Output

nice(aov_model)
## Anova Table (Type 3 tests)
## 
## Response: belong
##   Effect      df  MSE         F  pes p.value
## 1 gender 2, 2160 0.36 23.18 *** .021   <.001
## ---
## 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

8 Visualize Results

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

# 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

9 Run Posthoc Tests (One-Way)

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

emmeans(aov_model, specs="gender", adjust="sidak")
##  gender emmean     SE   df lower.CL upper.CL
##  f        3.26 0.0151 2160     3.22     3.30
##  m        3.06 0.0257 2160     3.00     3.12
##  nb       3.34 0.1080 2160     3.08     3.60
## 
## Confidence level used: 0.95 
## Conf-level adjustment: sidak method for 3 estimates
pairs(emmeans(aov_model, specs="gender", adjust="sidak"))
##  contrast estimate     SE   df t.ratio p.value
##  f - m      0.1995 0.0298 2160   6.697  <.0001
##  f - nb    -0.0824 0.1090 2160  -0.757  0.7297
##  m - nb    -0.2820 0.1110 2160  -2.542  0.0298
## 
## 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 predicting that there is a significant difference in the means of the sense of belonging across gender groups (males, females, and nonbinary participants), we used a One-Way ANOVA. Our data was unbalanced, with many more female participants represented in our survey (n = 1585) than male participants (n = 547) and nonbinary participants (n = 31). This significantly reduces the power of our test and increases the chances of a Type II error. We also identified no outliers following visual analysis of Cook’s Distance and Residuals VS Leverage plots. A significant Levene’s test (p = .035) 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.

Posthoc tests using Sidak’s adjustment revealed that nonbinary participants (M = 3.34, SE = .11) reported significantly greater sense of belonging than male participants (M = 3.06, SE = .03), but not significantly more than female participants (M = 3.26, SE = .02). Female participants reported significantly greater belonging than male participants (see Figure 1 for a comparison).

References

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