#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 modify variables or add new variables:
## let(mtcars, new_var = 42, new_var2 = new_var*hp) %>% head()
##
## Use 'expss_output_rnotebook()' to display tables inside R Notebooks.
## 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 at least 3 levels) OR a two-way ANOVA (two IVs, each with 2 levels).
One-Way Hypothesis: There will be a significant difference in feelings of maturity by people’s level of political party, between democrat, republican, and independent.
IV = political party DV = maturity
# 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': 3112 obs. of 8 variables:
## $ ResponseID : chr "R_BJN3bQqi1zUMid3" "R_2TGbiBXmAtxywsD" "R_12G7bIqN2wB2N65" "R_39pldNoon8CePfP" ...
## $ gender : chr "f" "m" "m" "f" ...
## $ party_rc : chr "democrat" "independent" "apolitical" "apolitical" ...
## $ moa_maturity: num 3.67 3.33 3.67 3 3.67 ...
## $ npi : num 0.6923 0.1538 0.0769 0.0769 0.7692 ...
## $ exploit : num 2 3.67 4.33 1.67 4 ...
## $ efficacy : num 3.4 3.4 2.2 2.8 3 2.4 2.3 3 3 3.7 ...
## $ 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)
# We're going to recode our party variable into 3 groups for the One-Way ANOVA: democrat, independent, republican
table(d$party_rc)
##
## apolitical democrat independent republican
## 436 1579 322 775
d <- subset(d, party_rc != "apolitical") # use subset() to remove all participants from the additional level
table(d$party_rc, useNA = "always") # verify that now there are ZERO participants in the additional level
##
## apolitical democrat independent republican <NA>
## 0 1579 322 775 0
d$party_rc <- droplevels(d$party_rc) # use droplevels() to drop the empty factor
table(d$party_rc, useNA = "always") # verify that now the entire factor level is removed
##
## democrat independent republican <NA>
## 1579 322 775 0
table(d$party_rc)
##
## democrat independent republican
## 1579 322 775
d$party_rc <- as.factor(d$party_rc)
# "drop levels" code copy/pasted from the t-test lab/HW.
# check that all our categorical variables of interest are now factors
str(d)
## 'data.frame': 2676 obs. of 8 variables:
## $ ResponseID : chr "R_BJN3bQqi1zUMid3" "R_2TGbiBXmAtxywsD" "R_2Quh0h3wxTjZjKP" "R_2CfdmFw1NTliv4e" ...
## $ gender : chr "f" "m" "f" "f" ...
## $ party_rc : Factor w/ 3 levels "democrat","independent",..: 1 2 2 1 1 1 2 2 1 1 ...
## $ moa_maturity: num 3.67 3.33 3.67 4 4 ...
## $ npi : num 0.6923 0.1538 0.6154 0.0769 0.0769 ...
## $ exploit : num 2 3.67 5.33 1 3.33 ...
## $ efficacy : num 3.4 3.4 2.3 3 3 3 3.1 3.6 2.9 2.5 ...
## $ row_id : Factor w/ 3112 levels "1","2","3","4",..: 1 2 7 8 9 12 13 15 17 18 ...
# check our DV skew and kurtosis
describe(d$moa_maturity)
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 2676 3.59 0.43 3.67 3.65 0.49 1.33 4 2.67 -1.17 1.63 0.01
# we'll use the describeBy() command to view our DV's skew and kurtosis across our IVs' levels
describeBy(d$moa_maturity, 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 1579 3.58 0.43 3.67 3.63 0.49 1.67 4 2.33 -1.02 0.95 0.01
## ------------------------------------------------------------
## group: independent
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 322 3.6 0.46 3.67 3.67 0.49 1.33 4 2.67 -1.5 3.37 0.03
## ------------------------------------------------------------
## group: republican
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 775 3.62 0.43 3.67 3.68 0.49 1.33 4 2.67 -1.31 2.11 0.02
# also use histograms to examine your continuous variable
hist(d$moa_maturity)
# REMEMBER your test's level of POWER is determined by your SMALLEST subsample
# One-Way
table(d$party_rc)
##
## democrat independent republican
## 1579 322 775
# 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(moa_maturity~party_rc, data = d)
## Levene's Test for Homogeneity of Variance (center = median)
## Df F value Pr(>F)
## group 2 0.76 0.4678
## 2673
# Not Significant
# 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(moa_maturity~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 unbalanced between the party type group levels. Our apolitical level of our variable slightly limits our power and increases our Type II error rate. It is not relevant to the hypothesis so we must move forward and remove it. Levene’s test was not significant (p= 0.5) for our three-level party-type variable with the One-Way ANOVA.
We identified and removed zero outliers for the One-Way ANOVA.
# One-Way
aov_model <- aov_ez(data = d,
id = "row_id",
between = c("party_rc"),
dv = "moa_maturity",
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: moa_maturity
## Effect df MSE F pes p.value
## 1 party_rc 2, 2673 0.18 2.80 + .002 .061
## ---
## 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")
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.58 0.0108 2673 3.55 3.60
## independent 3.60 0.0239 2673 3.55 3.66
## republican 3.62 0.0154 2673 3.58 3.66
##
## 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.0289 0.0263 2673 -1.099 0.5149
## democrat - republican -0.0432 0.0188 2673 -2.294 0.0568
## independent - republican -0.0144 0.0285 2673 -0.504 0.8692
##
## P value adjustment: tukey method for comparing a family of 3 estimates
To test our hypothesis that there will be a significant difference in feelings of maturity by people’s level of political party, between democrat, republican, and independent, we used a one-way ANOVA. Our data was unbalanced, with many more people who identify as democrats participating in our survey (n = 1579) than who are republican (n = 775) or independent (n = 332). This reduces the power of our test and increases the chances of a Type II error. We removed no outliers following visual analysis of Cook’s Distance and Residuals VS Leverage plots. A nonsignificant Levene’s test (p = 0.5) also indicates that our data does not violate the assumption of homogeneity of variance; see Figure 1 for comparison.
```
References
Cohen J. (1988). Statistical Power Analysis for the Behavioral Sciences. New York, NY: Routledge Academic.