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
library(expss) # for the cross_cases() command
library(car) # for the leveneTest() command
library(afex) # to run the ANOVA 
library(ggbeeswarm) # to run plot results
library(emmeans) # for posthoc tests

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)

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 (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.

3 One-Way ANOVA

3.1 State Your Hypothesis

We predict that there will be a significant difference in belonging by race, between White, Hispanic, and Black individuals.

3.2 Check Your Variables

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

str(d)
## 'data.frame':    3157 obs. of  8 variables:
##  $ ResponseID: chr  "R_BJN3bQqi1zUMid3" "R_2TGbiBXmAtxywsD" "R_12G7bIqN2wB2N65" "R_39pldNoon8CePfP" ...
##  $ race_rc   : chr  "white" "white" "white" "other" ...
##  $ gender    : chr  "f" "m" "m" "f" ...
##  $ swb       : num  4.33 4.17 1.83 5.17 3.67 ...
##  $ mindful   : num  2.4 1.8 2.2 2.2 3.2 ...
##  $ belong    : num  2.8 4.2 3.6 4 3.4 4.2 3.9 3.6 2.9 2.5 ...
##  $ socmeduse : int  47 23 34 35 37 13 37 43 37 29 ...
##  $ 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$race_rc <- as.factor(d$race_rc) 
d$row_id <- as.factor(d$row_id)


# check that our categorical variables of interest are now factors
str(d)
## 'data.frame':    3157 obs. of  8 variables:
##  $ ResponseID: chr  "R_BJN3bQqi1zUMid3" "R_2TGbiBXmAtxywsD" "R_12G7bIqN2wB2N65" "R_39pldNoon8CePfP" ...
##  $ race_rc   : Factor w/ 7 levels "asian","black",..: 7 7 7 6 7 7 7 7 4 4 ...
##  $ gender    : chr  "f" "m" "m" "f" ...
##  $ swb       : num  4.33 4.17 1.83 5.17 3.67 ...
##  $ mindful   : num  2.4 1.8 2.2 2.2 3.2 ...
##  $ belong    : num  2.8 4.2 3.6 4 3.4 4.2 3.9 3.6 2.9 2.5 ...
##  $ socmeduse : int  47 23 34 35 37 13 37 43 37 29 ...
##  $ row_id    : Factor w/ 3157 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 3157 3.23 0.61    3.3    3.25 0.59 1.3   5   3.7 -0.26    -0.12 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$race_rc)
## 
##  Descriptive statistics by group 
## group: asian
##    vars   n mean   sd median trimmed  mad min max range  skew kurtosis   se
## X1    1 209 3.26 0.57    3.3    3.27 0.59 1.5 4.5     3 -0.31     0.08 0.04
## ------------------------------------------------------------ 
## group: black
##    vars   n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 247 2.87 0.64    2.9    2.86 0.59 1.3   5   3.7  0.2      0.1 0.04
## ------------------------------------------------------------ 
## group: hispanic
##    vars   n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 283 2.97 0.56      3    2.97 0.59 1.3 4.4   3.1 -0.1        0 0.03
## ------------------------------------------------------------ 
## group: multiracial
##    vars   n mean   sd median trimmed  mad min max range  skew kurtosis   se
## X1    1 291 3.17 0.63    3.2    3.19 0.59 1.4 4.6   3.2 -0.32    -0.36 0.04
## ------------------------------------------------------------ 
## group: nativeamer
##    vars  n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 12 2.98 0.48   2.85    2.94 0.44 2.4 3.9   1.5 0.58    -1.15 0.14
## ------------------------------------------------------------ 
## group: other
##    vars  n mean   sd median trimmed  mad min max range  skew kurtosis   se
## X1    1 97    3 0.63      3    3.01 0.44 1.4 4.6   3.2 -0.15    -0.04 0.06
## ------------------------------------------------------------ 
## group: white
##    vars    n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 2018 3.33 0.57    3.4    3.35 0.59 1.4 4.9   3.5 -0.3    -0.03 0.01
# also use histograms to examine your continuous variable
hist(d$belong)

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

table(d$race_rc, useNA = "always") # verify that now there are ZERO participants in the additional level
## 
##       asian       black    hispanic multiracial  nativeamer       other 
##           0         247         283         291          12          97 
##       white        <NA> 
##        2018           0
 d$race_rc<- droplevels(d$race_rc) # use droplevels() to drop the empty factor

table(d$race_rc, useNA = "always") # verify that now the entire factor level is removed 
## 
##       black    hispanic multiracial  nativeamer       other       white 
##         247         283         291          12          97        2018 
##        <NA> 
##           0
d <- subset(d,race_rc  != "multiracial") # use subset() to remove all participants from the additional level

table(d$race_rc, useNA = "always") # verify that now there are ZERO participants in the additional level
## 
##       black    hispanic multiracial  nativeamer       other       white 
##         247         283           0          12          97        2018 
##        <NA> 
##           0
 d$race_rc<- droplevels(d$race_rc) # use droplevels() to drop the empty factor

table(d$race_rc, useNA = "always") # verify that now the entire factor level is removed 
## 
##      black   hispanic nativeamer      other      white       <NA> 
##        247        283         12         97       2018          0
d <- subset(d,race_rc  != "nativeamer") # use subset() to remove all participants from the additional level

table(d$race_rc, useNA = "always") # verify that now there are ZERO participants in the additional level
## 
##      black   hispanic nativeamer      other      white       <NA> 
##        247        283          0         97       2018          0
 d$race_rc<- droplevels(d$race_rc) # use droplevels() to drop the empty factor

table(d$race_rc, useNA = "always") # verify that now the entire factor level is removed 
## 
##    black hispanic    other    white     <NA> 
##      247      283       97     2018        0
d <- subset(d,race_rc  != "other") # use subset() to remove all participants from the additional level

table(d$race_rc, useNA = "always") # verify that now there are ZERO participants in the additional level
## 
##    black hispanic    other    white     <NA> 
##      247      283        0     2018        0
 d$race_rc<- droplevels(d$race_rc) # use droplevels() to drop the empty factor

table(d$race_rc, useNA = "always") # verify that now the entire factor level is removed 
## 
##    black hispanic    white     <NA> 
##      247      283     2018        0
d <- subset(d,race_rc  != "<NA>") # use subset() to remove all participants from the additional level

table(d$race_rc, useNA = "always") # verify that now there are ZERO participants in the additional level
## 
##    black hispanic    white     <NA> 
##      247      283     2018        0
 d$race_rc<- droplevels(d$race_rc) # use droplevels() to drop the empty factor

table(d$race_rc, useNA = "always") # verify that now the entire factor level is removed 
## 
##    black hispanic    white     <NA> 
##      247      283     2018        0

3.3 Check Your Assumptions

3.3.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.

3.3.2 Check levels of IVs

table(d$race_rc)
## 
##    black hispanic    white 
##      247      283     2018
# REMEMBER your test's level of POWER is determined by your SMALLEST subsample

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

3.3.3.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))  # NOTE: Participant 1108 is not truly problematic in the Lab, but we are going to removed them for demonstration.

# 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~x, where y is our DV, x is our IV

reg_model <- lm(belong~race_rc, data =d) 

3.3.3.2 Check for outliers

# Cook's distance
plot(reg_model,4)

# Residuals VS Leverage
plot(reg_model,5)

# IF you find outliers, go back up to line 114 or 117 and remove it/them, then re-run the reg_model code

3.3.4 Check homogeneity of variance

# use the leveneTest() command from the car package to test homogeneity of variance
# uses the 'formula' setup: formula is y~x, where y is our DV and x is our IV 
leveneTest(belong~race_rc, data =d)
## Levene's Test for Homogeneity of Variance (center = median)
##         Df F value Pr(>F)
## group    2  2.2126 0.1096
##       2545

3.3.5 Issues with My Data

Our cell sizes are unbalanced between the race group levels. Our smallest sample size for one of the levels of our variable ( n = 247 ) limits our power and increases our type II error rate. Additionally ther are more white partici[ants ( n = 2018)

Levene’s test was not significant for our three-level race variable with the One-Way ANOVA, indicating there was homogeneity of variance.

[UPDATE this section in your HW.]

3.4 Run a One-Way ANOVA

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

3.5 View One-Way Output

nice(aov_model)
## Anova Table (Type 3 tests)
## 
## Response: belong
##    Effect      df  MSE          F  pes p.value
## 1 race_rc 2, 2545 0.33 107.79 *** .078   <.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

3.6 Visualize One-Way Results

afex_plot(aov_model, x = "race_rc")

3.7 Run One-Way Posthoc Tests

Remember: We 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="race_rc")
##  race_rc  emmean     SE   df lower.CL upper.CL
##  black      2.87 0.0368 2545     2.80     2.94
##  hispanic   2.97 0.0344 2545     2.90     3.03
##  white      3.33 0.0129 2545     3.31     3.36
## 
## Confidence level used: 0.95
pairs(emmeans(aov_model, specs="race_rc", adjust="tukey"))
##  contrast         estimate     SE   df t.ratio p.value
##  black - hispanic  -0.0945 0.0504 2545  -1.875  0.1460
##  black - white     -0.4619 0.0390 2545 -11.838 <0.0001
##  hispanic - white  -0.3673 0.0367 2545  -9.999 <0.0001
## 
## P value adjustment: tukey method for comparing a family of 3 estimates

3.8 Write Up One-Way ANOVA Results

To test our hypothesis thatthere will be a significant difference in belonging by race (White, Hispanic and Black), we used a one-way ANOVA. Our data was unbalanced with many more White individial participating in our survey (n = 2018) than who were Black (n = 247) or Hispanic (n =283). This can reduce power, and potentially increase the chances of a Type II error. We did not detect any outliers in our visual analysis of Cooks Distance and Residuals VS Leverage plots. Levene’s test was not significant ( p = .110) for our three-level race variable with the One-Way ANOVA, indicating there was homogeneity of variance

We found a significant effect of race, F(2, 2545) = 107.79, p<.001 , ηp2 = .078 (trivial effect; Cohen, 1988). Posthoc tests using Tukey HSD adjustment revealed that participants who were Hispanic (M = 2.97, SE =.03) reported more belonging than those who were Black (M = 2.87, SE =..03) but less belonging than those who were White (M = 3.33, SE =.01); participants who were White reported higher belonging levels overall (see Figure 2 for a comparison).

References

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