#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 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
## 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 at least 3 levels) OR a two-way ANOVA (two IVs, each with 2 levels). You will need to specify your hypothesis and customize your code based on the choice you make (i.e., delete code that is not relevant). We will run BOTH versions in the lab for illustrative purposes.
One-Way Hypothesis: We predict that there will be a significant difference in people’s level of felt companionship based on the type of pet they own (dog, cat, rabbit).
‘IV = pet type ownership’ ‘DV = companionship’
Two-Way Hypothesis: We predict that there will a significant difference in people’s level of felt companionship based on the type of pet they own (dog, cat) and their race/ethnicity (white, persons of color). We also predict that there will be a significant interaction between pet type and partipant race/ethnicity.
IV1 = Pet Type Ownership IV2 = Particpant Race DV = Companionship
I HAD TO MOVE THE FOLLOWING LINES UP FOR IT TO LET ME KNIT, RSTUDIO HAS BEEN THROWING A FIT ALL DAY ABOUT RANDOM THINGS. ## 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 2 error) #- Homogeneity of variance should be assured (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.
# 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) # DELETE LINE IF DOING ONE-WAY FOR HW
d$row_id <- as.factor(d$row_id)
# We're going to recode our race variable into two groups for the Two-Way ANOVA: 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)
# For your HW, you can choose to combine levels like we did here, OR you can simply choose which existing levels you want to compare/test -- to do this option, you'll need to copy/paste the "drop levels" code from the t-test lab/HW and delete the recoding code line above.
# 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) # DELETE LINE IF DOING ONE-WAY FOR HW
##
## 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)
### Check levels of IVs
# One-Way
table(d$pet)
##
## cat dog rabbit
## 197 1020 33
# Two-Way
# 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
# FOR TWO-WAY ONLY (here to end of code chunk): our small number of participants owning rabbits is going to hurt us. We will create a new dataframe for the two-way analysis and call it d_twoway and remove the rabbit owning Ps.
d_twoway <- subset(d, pet != "rabbit")
d_twoway$pet <- droplevels(d_twoway$pet)
cross_cases(d_twoway, pet, poc) # double-checking changes we made
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_twoway)
## 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_twoway) #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 pet 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 3 level pet type variable with the one-way ANOVA. We are acknowledging this and continuing with the analysis anyway for class purposes.
We identified and removed a single outlier for the One-Way ANOVA.
[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_twoway,
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 [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 = "pet")
# Two-Way
afex_plot(aov_model2, x = "pet", trace = "poc")
afex_plot(aov_model2, x = "poc", trace = "pet")
# NOTE: for the Two-Way, we will decide which plot version makes the MOST SENSE based on the data / rationale when we 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="pet", adjust="sidak")
## 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="sidak"))
## 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 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.
# IV1 main effect
emmeans(aov_model2, specs="pet", adjust="sidak")
## NOTE: Results may be misleading due to involvement in interactions
## pet emmean SE df lower.CL upper.CL
## cat 2.57 0.0813 1195 2.38 2.75
## dog 3.04 0.0365 1195 2.96 3.12
##
## Results are averaged over the levels of: poc
## Confidence level used: 0.95
## Conf-level adjustment: sidak method for 2 estimates
pairs(emmeans(aov_model2, specs="pet", adjust="sidak"))
## NOTE: Results may be misleading due to involvement in interactions
## contrast estimate SE df t.ratio p.value
## cat - dog -0.474 0.0892 1195 -5.320 <.0001
##
## Results are averaged over the levels of: poc
# IV2 main effect -- NOTE in the lab "POC" did NOT have a main effect, so we are looking at the posthoc for demo purposes only.
emmeans(aov_model2, specs="poc", adjust="sidak")
## NOTE: Results may be misleading due to involvement in interactions
## 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="sidak"))
## 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 will be a significant difference in people’s level of felt companionship based on the pet ownership type (dog, cat, rabbit), 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 therefore 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 = 0.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 despite these issues for the purpose of this class.
We found a significant effect of pet type, F(2, 1246) = 27.54, p < 0.001, ηp2 = 0.42 (small effect size; Cohen, 1988). Posthoc tests using Sidak’s adjustment revealed that participants who own a dog (M = 2.97, SE = 0.03) reported more companionship than those who own a cat (M = 2.60, SE = 0.07) but less companionship than those who own a rabbit (M = 3.79, SE = 0.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 ANOVA. Our data met most of the assumptions of the test, although our data was unbalanced, with many more people who own a dog participating in our survey (n = 1020) than those who own a cat (n = 197).
As predicted, we found a significant difference for pet type, F(1, 1195) = 28.31, p <0.001, ηp2 = 0.023 (small effect size; Cohen, 1988). As predicted, dog owners (M = 3.04, SE = 0.04) reported significantly more companionship than cat owners (M = 2.57, SE = 0.08). Contrary to our expectations, we did not find a significant main effect for race (p = 0.453).
Lastly, we found marginal support for an interaction between pet type and race (see Figure 2), F(1, 1195) = 3.43, p = 0.64, ηp2 = 0.003 (trivial effect size; Cohen, 1988). When comparing by race, people of color who own a dog (M = 3.16, SE = 0.07) reported significantly more companionship than people of color who own a cat (M = 2.52, SE = 0.14; p > 0.001), as did white dog owners (M = 2.93, SE = 0.03) compared to white cat owners (M = 2.63, SE = 0.08; p <0.001). When comparing by pet ownership, people of color who own a dog reported significantly more companionship than White dog owners (p <0.01), while people of color and White … owners reported … levels of companionship (p 0.546).
References
Cohen J. (1988). Statistical Power Analysis for the Behavioral Sciences. New York, NY: Routledge Academic.