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 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
## 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 people’s level of stress based on their perceived attainability of the American Dream (American dream is important and achievable for me, American Dream is not important but achievable for me, American Dream is important but maybe not achievable for me).

4 Check Your Variables

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

str(d)
## 'data.frame':    3139 obs. of  8 variables:
##  $ ResponseID: chr  "R_BJN3bQqi1zUMid3" "R_2TGbiBXmAtxywsD" "R_12G7bIqN2wB2N65" "R_39pldNoon8CePfP" ...
##  $ efficacy  : num  3.4 3.4 2.2 2.8 3 2.4 2.3 3 3 3.7 ...
##  $ swb       : num  4.33 4.17 1.83 5.17 3.67 ...
##  $ 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 ...
##  $ usdream   : chr  "american dream is important and achievable for me" "american dream is important and achievable for me" "american dream is not important and maybe not achievable for me" "american dream is not important and maybe not achievable for me" ...
##  $ income    : chr  "1 low" "1 low" "rather not say" "rather not say" ...
##  $ 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$usdream <- as.factor(d$usdream) 
d$row_id <- as.factor(d$row_id)


# usdream variable has 5 levels, so I'm dropping 2
table(d$usdream)
## 
##               american dream is important and achievable for me 
##                                                            1455 
##     american dream is important but maybe not achievable for me 
##                                                             341 
## american dream is not important and maybe not achievable for me 
##                                                             584 
##        american dream is not important but is achievable for me 
##                                                             182 
##                            not sure if american dream important 
##                                                             577
d <- subset(d, usdream  != "not sure if american dream important")
table(d$usdream, useNA = "always")
## 
##               american dream is important and achievable for me 
##                                                            1455 
##     american dream is important but maybe not achievable for me 
##                                                             341 
## american dream is not important and maybe not achievable for me 
##                                                             584 
##        american dream is not important but is achievable for me 
##                                                             182 
##                            not sure if american dream important 
##                                                               0 
##                                                            <NA> 
##                                                               0
d$usdream <- droplevels(d$usdream)
table(d$usdream, useNA = "always")
## 
##               american dream is important and achievable for me 
##                                                            1455 
##     american dream is important but maybe not achievable for me 
##                                                             341 
## american dream is not important and maybe not achievable for me 
##                                                             584 
##        american dream is not important but is achievable for me 
##                                                             182 
##                                                            <NA> 
##                                                               0
d <- subset(d, usdream  != "american dream is not important and maybe not achievable for me")
table(d$usdream, useNA = "always")
## 
##               american dream is important and achievable for me 
##                                                            1455 
##     american dream is important but maybe not achievable for me 
##                                                             341 
## american dream is not important and maybe not achievable for me 
##                                                               0 
##        american dream is not important but is achievable for me 
##                                                             182 
##                                                            <NA> 
##                                                               0
d$usdream <- droplevels(d$usdream)
table(d$usdream, useNA = "always")
## 
##           american dream is important and achievable for me 
##                                                        1455 
## american dream is important but maybe not achievable for me 
##                                                         341 
##    american dream is not important but is achievable for me 
##                                                         182 
##                                                        <NA> 
##                                                           0
# check that all our categorical variables of interest are now factors
str(d)
## 'data.frame':    1978 obs. of  8 variables:
##  $ ResponseID: chr  "R_BJN3bQqi1zUMid3" "R_2TGbiBXmAtxywsD" "R_2Quh0h3wxTjZjKP" "R_2CfdmFw1NTliv4e" ...
##  $ efficacy  : num  3.4 3.4 2.3 3 3 3 3.1 3.9 3.3 2.8 ...
##  $ swb       : num  4.33 4.17 3.67 5.5 5 ...
##  $ belong    : num  2.8 4.2 3.9 3.6 2.9 3.1 2.4 3.5 3.8 3.5 ...
##  $ stress    : num  3.3 3.3 3.3 2.4 2.9 2.5 3.5 3.3 3 3.2 ...
##  $ usdream   : Factor w/ 3 levels "american dream is important and achievable for me",..: 1 1 2 3 1 1 1 3 3 1 ...
##  $ income    : chr  "1 low" "1 low" "1 low" "1 low" ...
##  $ row_id    : Factor w/ 3139 levels "1","2","3","4",..: 1 2 7 8 9 12 13 25 27 28 ...
# check our DV skew and kurtosis
describe(d$stress)
##    vars    n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 1978 2.99 0.59      3    2.99 0.59 1.3 4.7   3.4 0.05    -0.14 0.01
# we'll use the describeBy() command to view our DV's skew and kurtosis across our IVs' levels
describeBy(d$stress, group = d$usdream)
## 
##  Descriptive statistics by group 
## group: american dream is important and achievable for me
##    vars    n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 1455 2.94 0.57    2.9    2.94 0.59 1.3 4.6   3.3    0    -0.03 0.01
## ------------------------------------------------------------ 
## group: american dream is important but maybe not achievable for me
##    vars   n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 341 3.26 0.57    3.2    3.25 0.59 1.7 4.7     3 0.05    -0.54 0.03
## ------------------------------------------------------------ 
## group: american dream is not important but is achievable for me
##    vars   n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 182 2.92 0.67    2.9    2.89 0.74 1.4 4.6   3.2 0.29    -0.46 0.05
# also use histograms to examine your continuous variable
hist(d$stress)

# 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$usdream)
## 
##           american dream is important and achievable for me 
##                                                        1455 
## american dream is important but maybe not achievable for me 
##                                                         341 
##    american dream is not important but is achievable for me 
##                                                         182
## 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)

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(stress~usdream, data = d)
## Levene's Test for Homogeneity of Variance (center = median)
##         Df F value   Pr(>F)   
## group    2  5.2085 0.005545 **
##       1975                    
## ---
## 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 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(stress~usdream, data = d) 

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 American Dream 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 attainability of American Dream variable with the One-Way ANOVA. We are ignoring this and continuing with the analysis anyway for this class.

6 Run an ANOVA

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

7 View Output

# One-Way
nice(aov_model)
## Anova Table (Type 3 tests)
## 
## Response: stress
##    Effect      df  MSE         F  pes p.value
## 1 usdream 2, 1974 0.34 43.50 *** .042   <.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 = "usdream")

9 Run Posthoc Tests (One-Way)

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

emmeans(aov_model, specs="usdream", adjust="tukey")
## Note: adjust = "tukey" was changed to "sidak"
## because "tukey" is only appropriate for one set of pairwise comparisons
##  usdream                                                     emmean     SE   df
##  american dream is important and achievable for me             2.94 0.0152 1974
##  american dream is important but maybe not achievable for me   3.26 0.0315 1974
##  american dream is not important but is achievable for me      2.92 0.0430 1974
##  lower.CL upper.CL
##      2.90     2.97
##      3.18     3.33
##      2.82     3.02
## 
## Confidence level used: 0.95 
## Conf-level adjustment: sidak method for 3 estimates
pairs(emmeans(aov_model, specs="usdream", adjust="tukey"))
##  contrast                                                                                                              
##  american dream is important and achievable for me - american dream is important but maybe not achievable for me       
##  american dream is important and achievable for me - american dream is not important but is achievable for me          
##  american dream is important but maybe not achievable for me - american dream is not important but is achievable for me
##  estimate     SE   df t.ratio p.value
##   -0.3201 0.0349 1974  -9.161 <0.0001
##    0.0184 0.0457 1974   0.403  0.9145
##    0.3385 0.0533 1974   6.349 <0.0001
## 
## 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 will be a significant difference in people’s level of stress based on their attainability of the American Dream (american dream is important and achievable for me, american dream is important but maybe not achievable for me, american dream is not important but is achievable for me), we used a one-way ANOVA. Our data was unbalanced, with many more people claiming the American Dream is both important and achievable for them (n = 1455) than who selected the American Dream is important but maybe not achievable for them (n = 341) or not important but is achievable for them (n = 182). 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 Cook’s Distance and Residuals VS Leverage plots. A significant Levene’s test (p = .006) 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 attainability of the American Dream, F(2, 1975) = 43.56, p < .001, ηp2 = .042 (small-medium effect size; Cohen, 1988). Posthoc tests using Tukey’s HSD adjustment revealed that participants who believe the American Dream is important and achievable (M = 2.94, SE = .02) reported more stress than those who believe the American Dream is not important but achievable (M = 2.92, SE = .04) but less stress than those who said the American Dream is important but maybe not achievable (M = 3.26, SE = .03); participants who reported the American Dream is important but maybe not achievable for them reported the highest amount of stress overall (see Figure 1 for a comparison).

References

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