#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 get total summary skip 'by' argument: take_all(mtcars, mean)
##
## 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
## 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'
# 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 (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 participants satisfaction with life by their level of education, more specifically the lower the satisfaction with life
1 High school diploma or less, and NO COLLEGE 2 Currently in college 3 Completed some college, but no longer in college 4 Complete 2 year College degree 5 Completed Bachelors Degree 6 Currently in graduate education 7 Completed some graduate degree
# 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': 3137 obs. of 8 variables:
## $ ResponseID: chr "R_BJN3bQqi1zUMid3" "R_2TGbiBXmAtxywsD" "R_12G7bIqN2wB2N65" "R_39pldNoon8CePfP" ...
## $ edu : chr "2 Currently in college" "5 Completed Bachelors Degree" "2 Currently in college" "2 Currently in college" ...
## $ party_rc : chr "democrat" "independent" "apolitical" "apolitical" ...
## $ 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 ...
## $ 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" ...
## $ npi : num 0.6923 0.1538 0.0769 0.0769 0.7692 ...
## $ 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$edu <- as.factor(d$edu)
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$edu)
##
## 1 High school diploma or less, and NO COLLEGE
## 58
## 2 Currently in college
## 2537
## 3 Completed some college, but no longer in college
## 35
## 4 Complete 2 year College degree
## 178
## 5 Completed Bachelors Degree
## 137
## 6 Currently in graduate education
## 133
## 7 Completed some graduate degree
## 59
d$edu2[d$edu == "1 High school diploma or less, and NO COLLEGE"] <- "no college"
d$edu2[d$edu == "2 Currently in college"] <- "in college"
d$edu2[d$edu == "3 Completed some college, but no longer in college"] <- "in college"
d$edu2[d$edu == "4 Complete 2 year College degree"] <- "in college"
d$edu2[d$edu == "5 Completed Bachelors Degree"] <- "completed college"
d$edu2[d$edu == "6 Currently in graduate education"] <- "completed college"
d$edu2[d$edu == "7 Completed some graduate degree"] <- "completed college"
table(d$edu2)
##
## completed college in college no college
## 329 2750 58
d$edu2 <- as.factor(d$edu2)
# check that all our categorical variables of interest are now factors
str(d)
## 'data.frame': 3137 obs. of 9 variables:
## $ ResponseID: chr "R_BJN3bQqi1zUMid3" "R_2TGbiBXmAtxywsD" "R_12G7bIqN2wB2N65" "R_39pldNoon8CePfP" ...
## $ edu : Factor w/ 7 levels "1 High school diploma or less, and NO COLLEGE",..: 2 5 2 2 2 2 5 2 2 2 ...
## $ party_rc : chr "democrat" "independent" "apolitical" "apolitical" ...
## $ 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 ...
## $ 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" ...
## $ npi : num 0.6923 0.1538 0.0769 0.0769 0.7692 ...
## $ row_id : Factor w/ 3137 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
## $ edu2 : Factor w/ 3 levels "completed college",..: 2 1 2 2 2 2 1 2 2 2 ...
# check our DV skew and kurtosis
describe(d$swb)
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 3137 4.48 1.32 4.67 4.53 1.48 1 7 6 -0.36 -0.47 0.02
# we'll use the describeBy() command to view our DV's skew and kurtosis across our IVs' levels
describeBy(d$swb, group = d$edu2)
##
## Descriptive statistics by group
## group: completed college
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 329 4.61 1.23 4.67 4.64 1.24 1 7 6 -0.24 -0.43 0.07
## ------------------------------------------------------------
## group: in college
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 2750 4.47 1.33 4.67 4.53 1.48 1 7 6 -0.36 -0.48 0.03
## ------------------------------------------------------------
## group: no college
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 58 4.06 1.58 4.17 4.11 1.73 1 7 6 -0.22 -0.94 0.21
# also use histograms to examine your continuous variable
hist(d$swb)
# and cross_cases() to examine your categorical variables' cell count
cross_cases(d,edu2)
| #Total | |
|---|---|
| edu2 | |
| completed college | 329 |
| in college | 2750 |
| no college | 58 |
| #Total cases | 3137 |
# REMEMBER your test's level of POWER is determined by your SMALLEST subsample
# One-Way
table(d$edu2)
##
## completed college in college no college
## 329 2750 58
# 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(swb~edu2, data = d)
## Levene's Test for Homogeneity of Variance (center = median)
## Df F value Pr(>F)
## group 2 4.3491 0.013 *
## 3134
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# 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.
reg_model <- lm(swb~edu2, data = d) #for One-Way
# Cook's distance
plot(reg_model, 4)
# Residuals VS Leverage
plot(reg_model, 5)
Our cell sizes are very unbalanced between the education type group levels. A small sample 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 education type variable with the one-way ANOVA. We are ignoring this and continuing with the analysis anyway for this class.
We did not identify any outliers in the One-Way ANOVA.
[UPDATE this section in your HW.]
# One-Way
aov_model <- aov_ez(data = d,
id = "ResponseID",
between = c("edu2"),
dv = "swb",
anova_table = list(es = "pes"))
## Contrasts set to contr.sum for the following variables: edu2
nice(aov_model)
## Anova Table (Type 3 tests)
##
## Response: swb
## Effect df MSE F pes p.value
## 1 edu2 2, 3134 1.75 4.59 * .003 .010
## ---
## 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
# One-Way
afex_plot(aov_model, x = "edu2")
ONLY run posthoc IF the ANOVA test is SIGNIFICANT! E.g., only run the posthoc tests on edu2 type if there is a main effect for pet type
emmeans(aov_model, specs="edu2", adjust="sidak")
## edu2 emmean SE df lower.CL upper.CL
## completed college 4.61 0.0728 3134 4.43 4.78
## in college 4.47 0.0252 3134 4.41 4.53
## no college 4.06 0.1730 3134 3.64 4.47
##
## Confidence level used: 0.95
## Conf-level adjustment: sidak method for 3 estimates
pairs(emmeans(aov_model, specs="edu2", adjust="sidak"))
## contrast estimate SE df t.ratio p.value
## completed college - in college 0.139 0.0771 3134 1.797 0.1706
## completed college - no college 0.551 0.1880 3134 2.928 0.0096
## in college - no college 0.412 0.1750 3134 2.352 0.0490
##
## P value adjustment: tukey method for comparing a family of 3 estimates
To test our hypothesis There will be a significant difference in participants satisfaction with life by their level of education, more specifically the lower the satisfaction with life (no college, college, completed college), we used a one-way ANOVA. Our data was unbalanced, with many more people who own attended college participating in our survey (n = 2750 ) than who completed college (n = 329) or did not attend college (n = 58). This significantly reduces the power of our test and increases the chances of a Type II error. We did not indentify any outliers following visual analysis of Cook’s Distance and Residuals VS Leverage plots. A significant Levene’s test (p = .001) 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 on education type, F(2, 3134) = 4.59, p = .010, ηp2 = .003 (small effect size; Cohen, 1988). Posthoc tests using tukey’s adjustment revealed that participants who are in college (M = 4.47, SE = 0.0252) reported more satisfaction with life than those who did not go to college (M = 4.06, SE = 0.1730) but less satisfaction with life than those who completed college (M = 4.61, SE = 0.0728); participants who own a completed college reported the highest amount of satisfaction with life overall (see Figure 1 for a comparison).
References
Cohen J. (1988). Statistical Power Analysis for the Behavioral Sciences. New York, NY: Routledge Academic.