#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 aggregate data: take(mtcars, mean_mpg = mean(mpg), by = am)
##
## 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'
# 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: We predict that there will be a significant difference in people’s self-efficacy scores based on their political affiliation (Democrat, republican, independent).
# 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': 1615 obs. of 8 variables:
## $ ResponseID: chr "R_12G7bIqN2wB2N65" "R_2CfdmFw1NTliv4e" "R_24kJPxVOxMshN3Q" "R_3JmBijdH1z82QU2" ...
## $ gender : chr "m" "f" "f" "f" ...
## $ party_rc : chr "apolitical" "democrat" "democrat" "apolitical" ...
## $ pipwd : num 2.33 3.53 3 3 3.13 ...
## $ swb : num 1.83 5.5 5 4.67 3 ...
## $ mindful : num 2.2 3 3.4 4.6 3.87 ...
## $ efficacy : num 2.2 3 3 3.3 3 3.1 2.9 2.9 2.4 2.8 ...
## $ 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$party_rc <- as.factor(d$party_rc)
d$row_id <- as.factor(d$row_id)
d <- subset(d, party_rc != "apolitical")
table(d$party_rc, useNA = "always")
##
## apolitical democrat independent republican <NA>
## 0 821 184 390 0
d$party_rc<- droplevels(d$party_rc)
table(d$party_rc, useNA = "always")
##
## democrat independent republican <NA>
## 821 184 390 0
# check that all our categorical variables of interest are now factors
str(d)
## 'data.frame': 1395 obs. of 8 variables:
## $ ResponseID: chr "R_2CfdmFw1NTliv4e" "R_24kJPxVOxMshN3Q" "R_2v0uaPOXYQlnqnk" "R_3lLnoV2mYVYHFvf" ...
## $ gender : chr "f" "f" "m" "f" ...
## $ party_rc : Factor w/ 3 levels "democrat","independent",..: 1 1 1 2 1 1 1 1 1 2 ...
## $ pipwd : num 3.53 3 3.13 2.33 2.33 ...
## $ swb : num 5.5 5 3 5.83 5.17 ...
## $ mindful : num 3 3.4 3.87 1.6 3.6 ...
## $ efficacy : num 3 3 3 3.1 2.9 2.4 2.8 3.3 2.7 3.7 ...
## $ row_id : Factor w/ 1615 levels "1","2","3","4",..: 2 3 5 6 8 9 10 12 14 15 ...
# check our DV skew and kurtosis
describe(d$efficacy)
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 1395 3.13 0.45 3.1 3.13 0.44 1.1 4 2.9 -0.32 0.64 0.01
# we'll use the describeBy() command to view our DV's skew and kurtosis across our IVs' levels
describeBy(d$efficacy, group =d$party_rc)
##
## Descriptive statistics by group
## group: democrat
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 821 3.1 0.46 3.1 3.11 0.44 1.1 4 2.9 -0.41 0.87 0.02
## ------------------------------------------------------------
## group: independent
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 184 3.12 0.46 3.1 3.12 0.44 1.8 4 2.2 -0.07 -0.17 0.03
## ------------------------------------------------------------
## group: republican
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 390 3.18 0.43 3.1 3.18 0.44 1.4 4 2.6 -0.19 0.34 0.02
# also use histograms to examine your continuous variable
hist(d$efficacy)
# and cross_cases() to examine your categorical variables' cell count
# REMEMBER your test's level of POWER is determined by your SMALLEST subsample
# One-Way
table(d$party_rc)
##
## democrat independent republican
## 821 184 390
# 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(efficacy~party_rc, data = d)
## Levene's Test for Homogeneity of Variance (center = median)
## Df F value Pr(>F)
## group 2 0.4307 0.6501
## 1392
# 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(efficacy~party_rc, 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 political affiliation 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 not significant for our three-level variable with the political affiliation variable with the One-Way ANOVA. We are ignoring this and continuing with the analysis anyway for this class.
We identified and did not need to remove any outliers for the One-Way ANOVA.
[UPDATE this section in your HW.]
# One-Way
aov_model <- aov_ez(data = d,
id = "ResponseID",
between = c("party_rc"),
dv = "efficacy",
anova_table = list(es = "pes"))
## Contrasts set to contr.sum for the following variables: party_rc
nice(aov_model)
## Anova Table (Type 3 tests)
##
## Response: efficacy
## Effect df MSE F pes p.value
## 1 party_rc 2, 1392 0.21 4.30 * .006 .014
## ---
## 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 = "party_rc")
# Two-Way
# 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
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="party_rc", adjust="sidak")
## party_rc emmean SE df lower.CL upper.CL
## democrat 3.10 0.0158 1392 3.06 3.14
## independent 3.12 0.0335 1392 3.04 3.20
## republican 3.18 0.0230 1392 3.13 3.24
##
## Confidence level used: 0.95
## Conf-level adjustment: sidak method for 3 estimates
pairs(emmeans(aov_model, specs="party_rc", adjust="sidak"))
## contrast estimate SE df t.ratio p.value
## democrat - independent -0.0245 0.0370 1392 -0.661 0.7861
## democrat - republican -0.0819 0.0279 1392 -2.933 0.0095
## independent - republican -0.0574 0.0406 1392 -1.414 0.3337
##
## P value adjustment: tukey method for comparing a family of 3 estimates
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.
```
To test our hypothesis that there will be a significant difference in people’s level self-efficacy based on their politcal party affiliation (Democrat, Republican, Independent), we used a one-way ANOVA. Our data was unbalanced, with many more people who are affiliated as a democrat participating in our survey (n = 821) than who are affiliated as a republican (n = 390) or affiliated as independent (n = 184). This significantly reduces the power of our test and increases the chances of a Type II error. We also did not need to remove any outliers following visual analysis of Cook’s Distance and Residuals VS Leverage plots. There was not a significant Levene’s test (p = 0.65) also indicates that our data does not violate the assumption of homogengeneity of variance. This suggests that there is not an increased chance of Type I error. We continued with our analysis for the purpose of this class.
We found a significant effect of political party affiliation, F(2, 1392) = 4.30, p =0.014, ηp2 =.006 (small effect size; Cohen, 1988). Posthoc tests using Sidak’s adjustment revealed that participants who identified as republicans (M = 3.18, SE = .02) reported significantly higher self-efficacy than those who identified as democrats (M = 3.10, SE = .02), p=.0095 but there was no significant differences between independents (M = 3.12, SE = .03); and the pther groups (see Figure 1 for a comparison).
References
Cohen J. (1988). Statistical Power Analysis for the Behavioral Sciences. New York, NY: Routledge Academic.