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 people’s level of satisfaction with life based on their income group (low, middle, high).

3.2 Check Your Variables

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

str(d)
## 'data.frame':    3034 obs. of  8 variables:
##  $ ResponseID      : chr  "R_BJN3bQqi1zUMid3" "R_2TGbiBXmAtxywsD" "R_12G7bIqN2wB2N65" "R_39pldNoon8CePfP" ...
##  $ income          : chr  "1 low" "1 low" "rather not say" "rather not say" ...
##  $ marriage5       : chr  "are currently divorced from one another" "are currently married to one another" "are currently married to one another" "are currently married to one another" ...
##  $ moa_independence: num  3.67 3.67 3.5 3 3.83 ...
##  $ moa_role        : num  3 2.67 2.5 2 2.67 ...
##  $ 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 ...
##  $ 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$income <- as.factor(d$income) 
d$row_id <- as.factor(d$row_id)


d <- subset(d, income != "rather not say")
table(d$income, useNA = "always")
## 
##          1 low       2 middle         3 high rather not say           <NA> 
##            845            852            515              0              0
d$income <- droplevels(d$income)
table(d$income, useNA = "always")
## 
##    1 low 2 middle   3 high     <NA> 
##      845      852      515        0
# check that our categorical variables of interest are now factors
str(d)
## 'data.frame':    2212 obs. of  8 variables:
##  $ ResponseID      : chr  "R_BJN3bQqi1zUMid3" "R_2TGbiBXmAtxywsD" "R_1QiKb2LdJo1Bhvv" "R_2Quh0h3wxTjZjKP" ...
##  $ income          : Factor w/ 3 levels "1 low","2 middle",..: 1 1 2 1 1 3 1 1 1 1 ...
##  $ marriage5       : chr  "are currently divorced from one another" "are currently married to one another" "are currently married to one another" "are currently married to one another" ...
##  $ moa_independence: num  3.67 3.67 3.83 4 4 ...
##  $ moa_role        : num  3 2.67 2.67 3.33 3.5 ...
##  $ swb             : num  4.33 4.17 3.67 3.67 5.5 ...
##  $ belong          : num  2.8 4.2 3.4 3.9 3.6 2.9 4.1 3 4.1 3.3 ...
##  $ row_id          : Factor w/ 3034 levels "1","2","3","4",..: 1 2 5 7 8 9 11 16 17 18 ...
# check our DV skew and kurtosis
describe(d$swb)
##    vars    n mean   sd median trimmed  mad min max range  skew kurtosis   se
## X1    1 2212  4.5 1.34   4.67    4.57 1.48   1   7     6 -0.41    -0.41 0.03
# we'll use the describeBy() command to view our DV's skew and kurtosis across our IVs' levels
describeBy(d$swb, group = d$income)
## 
##  Descriptive statistics by group 
## group: 1 low
##    vars   n mean   sd median trimmed  mad min max range  skew kurtosis   se
## X1    1 845 4.23 1.32   4.33    4.27 1.48   1   7     6 -0.24    -0.48 0.05
## ------------------------------------------------------------ 
## group: 2 middle
##    vars   n mean   sd median trimmed  mad min max range  skew kurtosis   se
## X1    1 852 4.59 1.32   4.83    4.67 1.24   1   7     6 -0.48    -0.35 0.05
## ------------------------------------------------------------ 
## group: 3 high
##    vars   n mean   sd median trimmed  mad min max range  skew kurtosis   se
## X1    1 515  4.8 1.32      5    4.89 1.24   1   7     6 -0.63    -0.05 0.06
# also use histograms to examine your continuous variable
hist(d$swb)

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$income)
## 
##    1 low 2 middle   3 high 
##      845      852      515
# 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 problamtic 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(swb~income, 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(swb~income, data = d)
## Levene's Test for Homogeneity of Variance (center = median)
##         Df F value Pr(>F)
## group    2  0.2792 0.7565
##       2209

3.3.5 Issues with My Data

Our cell sizes are slightly unbalanced between the pet type group levels. A small sample size for one of the levels of our variable (high income, n = 515) limits our power and increases our type II error rate.

Levene’s test was significant for our three-level pet type variable with the One-Way ANOVA. We are ignoring and continuing with the analysis for the purpose of this class.

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

[UPDATE this section in your HW.]

3.4 Run a One-Way ANOVA

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

3.5 View One-Way Output

nice(aov_model)
## Anova Table (Type 3 tests)
## 
## Response: swb
##   Effect      df  MSE         F  pes p.value
## 1 income 2, 2209 1.74 32.63 *** .029   <.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 = "income" )

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="income")
##  income   emmean     SE   df lower.CL upper.CL
##  1 low      4.23 0.0454 2209     4.14     4.32
##  2 middle   4.59 0.0452 2209     4.50     4.68
##  3 high     4.80 0.0581 2209     4.68     4.91
## 
## Confidence level used: 0.95
pairs(emmeans(aov_model, specs="income", adjust="tukey"))
##  contrast          estimate     SE   df t.ratio p.value
##  1 low - 2 middle    -0.360 0.0640 2209  -5.626 <0.0001
##  1 low - 3 high      -0.565 0.0737 2209  -7.670 <0.0001
##  2 middle - 3 high   -0.205 0.0736 2209  -2.788  0.0148
## 
## P value adjustment: tukey method for comparing a family of 3 estimates

3.8 Write Up One-Way ANOVA Results

To test our hypothesis that there will be a significant DIFFERENCE in people’s level of satisfaction with life based on their income group (high, middle, low), we used a one-way ANOVA. Our data was unbalanced, with many less people who were high class participating in our survey (n = 515 ) than those in low class (n = 845) or middle class (n = 852). This significantly reduces the power of our test and increases the chances of a Type II error. We also identified and removed a single outlier following visual analysis of cooks distance and residual vs Leverage plots. A significant Levene’s test (p = <.001 ) also indicates that our data fails 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 income group, F(2, 2209) = 32.63, p <.001 , ηp2 = .029 (small effect; Cohen, 1988). Posthoc tests using Tukey’s HSD adjustment revealed that participants in the middle income group (M = 4.59, SE = .05) reported more satisfaction with life than those in a low class (M = 4.23, SE = .05) but less companionship than those in the high class (M = 4.80, SE = .06 ); participants in the high class reported the highest amount of satisfaction with life overall (see Figure 1 for a comparison).