#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
##
## Use magrittr pipe '%>%' to chain several operations:
## mtcars %>%
## let(mpg_hp = mpg/hp) %>%
## take(mean(mpg_hp), by = am)
##
##
## Attaching package: 'maditr'
## The following object is masked from 'package:base':
##
## sort_by
##
## 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/anova_labdata.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 more than 2 levels) OR a two-way/factorial ANOVA (at least two IVs). 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 effect of the type of pet one owns on people’s felt companionship.
Two-Way: We predict that there will significant effects of the type of pet one owns and one’s race on people’s felt companionship. We also predict that there will be a significant interaction between pet type and race.
# 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': 1250 obs. of 7 variables:
## $ X : int 1 20 30 31 33 57 68 81 86 104 ...
## $ pet : chr "dog" "cat" "dog" "dog" ...
## $ race : chr "white" "white" "white" "white" ...
## $ companionship : num 3.25 3.75 1 3.25 2 4 3.75 1.25 2.5 2.5 ...
## $ pet_noise : num 1.33 3.33 1 2.33 1.11 ...
## $ life_happiness: num 2.3 1.6 3.9 1.7 3.9 1.8 1.3 3.5 2.6 3 ...
## $ 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$pet <- as.factor(d$pet)
d$race <- as.factor(d$race)
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$race)
##
## asian black mideast multiracial other prefer_not
## 139 26 12 65 11 18
## white
## 979
d$poc[d$race == "asian"] <- "poc"
d$poc[d$race == "black"] <- "poc"
d$poc[d$race == "mideast"] <- "poc"
d$poc[d$race == "multiracial"] <- "poc"
d$poc[d$race == "other"] <- "poc"
d$poc[d$race == "prefer_not"] <- NA
d$poc[d$race == "white"] <- "white"
table(d$poc)
##
## poc white
## 253 979
d$poc <- as.factor(d$poc)
# check that all our categorical variables of interest are now factors
str(d)
## 'data.frame': 1250 obs. of 8 variables:
## $ X : int 1 20 30 31 33 57 68 81 86 104 ...
## $ pet : Factor w/ 3 levels "cat","dog","rabbit": 2 1 2 2 2 2 1 1 2 2 ...
## $ race : Factor w/ 7 levels "asian","black",..: 7 7 7 7 7 7 7 7 7 2 ...
## $ companionship : num 3.25 3.75 1 3.25 2 4 3.75 1.25 2.5 2.5 ...
## $ pet_noise : num 1.33 3.33 1 2.33 1.11 ...
## $ life_happiness: num 2.3 1.6 3.9 1.7 3.9 1.8 1.3 3.5 2.6 3 ...
## $ row_id : Factor w/ 1250 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
## $ poc : Factor w/ 2 levels "poc","white": 2 2 2 2 2 2 2 2 2 1 ...
# check our DV skew and kurtosis
describe(d$companionship)
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 1250 2.93 0.95 3 2.92 1.11 1 5 4 0.09 -0.74 0.03
# we'll use the describeBy() command to view our DV's skew and kurtosis across our IVs' levels
describeBy(d$companionship, group = d$pet)
##
## Descriptive statistics by group
## group: cat
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 197 2.6 0.89 2.5 2.55 0.74 1 5 4 0.5 -0.24 0.06
## ------------------------------------------------------------
## group: dog
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 1020 2.97 0.95 3 2.97 1.11 1 5 4 0.04 -0.73 0.03
## ------------------------------------------------------------
## group: rabbit
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 33 3.71 0.73 3.75 3.77 0.74 1.25 5 3.75 -1.06 1.89 0.13
describeBy(d$companionship, group = d$poc)
##
## Descriptive statistics by group
## group: poc
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 253 3.05 0.96 3 3.06 1.11 1 5 4 0.02 -0.76 0.06
## ------------------------------------------------------------
## group: white
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 979 2.9 0.95 3 2.89 1.11 1 5 4 0.1 -0.75 0.03
# also use histograms to examine your continuous variable
hist(d$companionship)
# and cross_cases() to examine your categorical variables' cell count
cross_cases(d, pet, poc)
poc | ||
---|---|---|
poc | white | |
pet | ||
cat | 42 | 153 |
dog | 205 | 799 |
rabbit | 6 | 27 |
#Total cases | 253 | 979 |
# REMEMBER your test's level of power is determined by your SMALLEST subsample
# One-Way
table(d$pet)
##
## cat dog rabbit
## 197 1020 33
# Two-Way
cross_cases(d, pet, poc)
poc | ||
---|---|---|
poc | white | |
pet | ||
cat | 42 | 153 |
dog | 205 | 799 |
rabbit | 6 | 27 |
#Total cases | 253 | 979 |
# our small number of participants owning rabbits is going to hurt us for the two-way anova, but it should be okay for the one-way anova
# so we'll create a new dataframe for the two-way analysis and call it d_tw
d_tw <- subset(d, pet != "rabbit")
d_tw$pet <- droplevels(d_tw$pet)
table(d_tw$pet)
##
## cat dog
## 197 1020
# double-check any changes we made
cross_cases(d_tw, pet, poc)
poc | ||
---|---|---|
poc | white | |
pet | ||
cat | 42 | 153 |
dog | 205 | 799 |
#Total cases | 247 | 952 |
# 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(companionship~pet, data = d)
## Levene's Test for Homogeneity of Variance (center = median)
## Df F value Pr(>F)
## group 2 4.4963 0.01133 *
## 1247
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# Two-Way
leveneTest(companionship~pet*poc, data = d_tw)
## Levene's Test for Homogeneity of Variance (center = median)
## Df F value Pr(>F)
## group 3 1.2775 0.2807
## 1195
# 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(companionship ~ pet, data = d) #for One-Way
reg_model2 <- lm(companionship ~ pet*poc, data = d_tw) #for Two-Way
# Cook's distance
plot(reg_model, 4)
# Residuals VS Leverage
plot(reg_model, 5)
# Cook's distance
plot(reg_model2, 4)
# Residuals vs Leverage
plot(reg_model2, 5)
Our cell sizes are very unbalanced between the 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 pet type variable. We are ignoring this and continuing with the analysis anyway for this class.
We identified and removed a single outlier.
[UPDATE this section in your HW.]
# One-Way
aov_model <- aov_ez(data = d,
id = "X",
between = c("pet"),
dv = "companionship",
anova_table = list(es = "pes"))
## Contrasts set to contr.sum for the following variables: pet
# Two-Way
aov_model2 <- aov_ez(data = d_tw,
id = "X",
between = c("pet","poc"),
dv = "companionship",
anova_table = list(es = "pes"))
## Warning: Missing values for 18 ID(s), which were removed before analysis:
## 490, 520, 1224, 1276, 1472, 2550, 3030, 3648, 5262, 6431, ... [showing first 10 only]
## Below the first few rows (in wide format) of the removed cases with missing data.
## X pet poc .
## # 67 490 dog <NA> 2.50
## # 68 520 dog <NA> 2.75
## # 151 1224 dog <NA> 1.25
## # 157 1276 dog <NA> 1.50
## # 182 1472 dog <NA> 2.00
## # 315 2550 dog <NA> 3.00
## Contrasts set to contr.sum for the following variables: pet, poc
nice(aov_model)
## Anova Table (Type 3 tests)
##
## Response: companionship
## Effect df MSE F pes p.value
## 1 pet 2, 1246 0.87 27.54 *** .042 <.001
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '+' 0.1 ' ' 1
nice(aov_model2)
## Anova Table (Type 3 tests)
##
## Response: companionship
## Effect df MSE F pes p.value
## 1 pet 1, 1195 0.87 28.31 *** .023 <.001
## 2 poc 1, 1195 0.87 0.56 <.001 .453
## 3 pet:poc 1, 1195 0.87 3.43 + .003 .064
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '+' 0.1 ' ' 1
ANOVA Effect Size 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 = "pet")
# Two-Way
afex_plot(aov_model2, x = "pet", trace = "poc")
afex_plot(aov_model2, x = "poc", trace = "pet")
# 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 posthocs 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="pet", adjust="tukey")
## Note: adjust = "tukey" was changed to "sidak"
## because "tukey" is only appropriate for one set of pairwise comparisons
## pet emmean SE df lower.CL upper.CL
## cat 2.60 0.0663 1246 2.44 2.75
## dog 2.97 0.0291 1246 2.90 3.04
## rabbit 3.79 0.1640 1246 3.40 4.18
##
## Confidence level used: 0.95
## Conf-level adjustment: sidak method for 3 estimates
pairs(emmeans(aov_model, specs="pet", adjust="tukey"))
## contrast estimate SE df t.ratio p.value
## cat - dog -0.379 0.0724 1246 -5.237 <.0001
## cat - rabbit -1.194 0.1770 1246 -6.734 <.0001
## dog - rabbit -0.815 0.1670 1246 -4.879 <.0001
##
## P value adjustment: tukey method for comparing a family of 3 estimates
Only run posthocs 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.
# IV1 main effect
emmeans(aov_model, specs="pet", adjust="tukey")
## Note: adjust = "tukey" was changed to "sidak"
## because "tukey" is only appropriate for one set of pairwise comparisons
## pet emmean SE df lower.CL upper.CL
## cat 2.60 0.0663 1246 2.44 2.75
## dog 2.97 0.0291 1246 2.90 3.04
## rabbit 3.79 0.1640 1246 3.40 4.18
##
## Confidence level used: 0.95
## Conf-level adjustment: sidak method for 3 estimates
pairs(emmeans(aov_model, specs="pet", adjust="tukey"))
## contrast estimate SE df t.ratio p.value
## cat - dog -0.379 0.0724 1246 -5.237 <.0001
## cat - rabbit -1.194 0.1770 1246 -6.734 <.0001
## dog - rabbit -0.815 0.1670 1246 -4.879 <.0001
##
## P value adjustment: tukey method for comparing a family of 3 estimates
# IV2 main effect -- NOTE in the lab "POC" did NOT have a main effect, but we are looking at the posthoc for demo purposes.
emmeans(aov_model2, specs="poc", adjust="tukey")
## NOTE: Results may be misleading due to involvement in interactions
## Note: adjust = "tukey" was changed to "sidak"
## because "tukey" is only appropriate for one set of pairwise comparisons
## poc emmean SE df lower.CL upper.CL
## poc 2.84 0.0791 1195 2.66 3.01
## white 2.77 0.0412 1195 2.68 2.86
##
## Results are averaged over the levels of: pet
## Confidence level used: 0.95
## Conf-level adjustment: sidak method for 2 estimates
pairs(emmeans(aov_model2, specs="poc", adjust="tukey"))
## NOTE: Results may be misleading due to involvement in interactions
## contrast estimate SE df t.ratio p.value
## poc - white 0.067 0.0892 1195 0.751 0.4527
##
## Results are averaged over the levels of: pet
# IV1 and IV2 interaction effect
emmeans(aov_model2, specs="pet", by="poc", adjust="sidak")
## poc = poc:
## pet emmean SE df lower.CL upper.CL
## cat 2.52 0.1440 1195 2.20 2.84
## dog 3.16 0.0652 1195 3.01 3.30
##
## poc = white:
## pet emmean SE df lower.CL upper.CL
## cat 2.62 0.0755 1195 2.45 2.79
## dog 2.93 0.0330 1195 2.85 3.00
##
## Confidence level used: 0.95
## Conf-level adjustment: sidak method for 2 estimates
pairs(emmeans(aov_model2, specs="pet", by="poc", adjust="sidak"))
## poc = poc:
## contrast estimate SE df t.ratio p.value
## cat - dog -0.639 0.1580 1195 -4.044 0.0001
##
## poc = white:
## contrast estimate SE df t.ratio p.value
## cat - dog -0.309 0.0824 1195 -3.753 0.0002
emmeans(aov_model2, specs="poc", by="pet", adjust="sidak")
## pet = cat:
## poc emmean SE df lower.CL upper.CL
## poc 2.52 0.1440 1195 2.20 2.84
## white 2.62 0.0755 1195 2.45 2.79
##
## pet = dog:
## poc emmean SE df lower.CL upper.CL
## poc 3.16 0.0652 1195 3.01 3.30
## white 2.93 0.0330 1195 2.85 3.00
##
## Confidence level used: 0.95
## Conf-level adjustment: sidak method for 2 estimates
pairs(emmeans(aov_model2, specs="poc", by="pet", adjust="sidak"))
## pet = cat:
## contrast estimate SE df t.ratio p.value
## poc - white -0.0982 0.1630 1195 -0.604 0.5463
##
## pet = dog:
## contrast estimate SE df t.ratio p.value
## poc - white 0.2321 0.0731 1195 3.175 0.0015
To test our hypothesis that there would be a significant effect of type of pet ownership on people’s companionship, we used a one-way ANOVA. Our data was unbalanced, with many more people who own a dog participating in our survey (n = 1020) than who own a cat (n = 197) or rabbit (n = 32). 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 Cook’s Distance and Residuals VS Leverage plots. A significant Levene’s test (p = .002) 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 pet type, F(2, 1246) = 27.54, p < .001, ηp2 = .042 (large effect size; Cohen, 1988). Posthoc tests using Sidak’s adjustment revealed that participants who own a dog (M = 2.97, SE = .03) reported more companionship than those who own a cat (M = 2.06, SE = .07) but less companionship than those who own a rabbit (M = 3.79, SE = .16); participants who own a rabbit reported the highest amount of companionship overall (see Figure 1 for a comparison).
To test our hypothesis that the type of pet one owns and one’s race would impact people’s felt companionship and would interact significantly, we used a two-way/factorial ANOVA. Our data met most of the assumptions of the test, although our data was unbalanced, with many more people who own dogs participating in our survey (n = 1020) than those who own cats (n = 197).
As predicted, we found a significant main effect for pet type, F(1, 1195) = 28.31, p < .001, ηp2 = .023 (small effect size; Cohen, 1988). As predicted, dog owners (M = 3.04, SE = .04) reported significantly more companionship than cat owners (M = 2.57, SE = .08). Contrary to our expectations, we did not find a significant main effect for race (p = .453).
Lastly, we found a marginal support for an interaction between pet type and race (see Figure 2), F(1, 1195) = 3.43, p = .064, ηp2 = .003 (trivial effect size; Cohen, 1988). When comparing by race, people of color who own dogs (M = 3.16, SE = .07) reported significantly more companionship than people of color who own cats (M = 2.52, SE = .14; p < .001), as did White dog owners (M = 2.93, SE = .03) compared to White cat owners (M = 2.62, SE = .08; p < .001). When comparing by pet ownership, people of color who own dogs reported significantly more companionship than White dog owners (p = .002), while people of color and White cat owners reported similar levels of companionship (p = .546).
References
Cohen J. (1988). Statistical Power Analysis for the Behavioral Sciences. New York, NY: Routledge Academic.