1 Loading Libraries

#install.packages("afex")
#install.packages("emmeans")
#install.packages("ggbeeswarm")
#install.packages("expss")

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
## Warning: package 'ggbeeswarm' was built under R version 4.5.2
library(emmeans) # for posthoc tests
## Welcome to emmeans.
## Caution: You lose important information if you filter this package's results.
## See '? untidy'

2 Importing Data

# 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)

3 State Your Hypothesis

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 level of isolation based on the participants’ income (low, middle, high).

4 Check Your Variables

# you only need to check the variables you're using in the current analysis

str(d)
## 'data.frame':    365 obs. of  8 variables:
##  $ X          : int  1 401 1390 2689 2752 2835 3935 4050 4058 4160 ...
##  $ ethnicity  : chr  "White - British, Irish, other" "Middle Eastern/Middle Eastern British - Arab, Turkish, other" "White - British, Irish, other" "White - British, Irish, other" ...
##  $ income     : chr  "3 high" "3 high" "3 high" "2 middle" ...
##  $ mfq_state  : num  3.62 5 3.5 3.12 3.88 ...
##  $ pas_covid  : num  3.22 4 2.89 5 3.56 ...
##  $ isolation_a: num  2.25 2.5 2.25 3.25 3.25 3.25 3 1 1 2 ...
##  $ pss        : num  3.25 2.25 2.75 4 3.25 2.5 4.5 2 1.75 2.25 ...
##  $ 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$income <- as.factor(d$income) 
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$income)
## 
##             1 low          2 middle            3 high prefer not to say 
##                45               173                97                50
# check that all our categorical variables of interest are now factors
str(d)
## 'data.frame':    365 obs. of  8 variables:
##  $ X          : int  1 401 1390 2689 2752 2835 3935 4050 4058 4160 ...
##  $ ethnicity  : chr  "White - British, Irish, other" "Middle Eastern/Middle Eastern British - Arab, Turkish, other" "White - British, Irish, other" "White - British, Irish, other" ...
##  $ income     : Factor w/ 4 levels "1 low","2 middle",..: 3 3 3 2 3 1 2 1 2 2 ...
##  $ mfq_state  : num  3.62 5 3.5 3.12 3.88 ...
##  $ pas_covid  : num  3.22 4 2.89 5 3.56 ...
##  $ isolation_a: num  2.25 2.5 2.25 3.25 3.25 3.25 3 1 1 2 ...
##  $ pss        : num  3.25 2.25 2.75 4 3.25 2.5 4.5 2 1.75 2.25 ...
##  $ row_id     : Factor w/ 365 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
# check our DV skew and kurtosis
describe(d$isolation_a)
##    vars   n mean  sd median trimmed  mad min max range skew kurtosis   se
## X1    1 365 1.69 0.7    1.5     1.6 0.74   1 3.5   2.5 0.85    -0.38 0.04
# we'll use the describeBy() command to view our DV's skew and kurtosis across our IVs' levels
describeBy(d$isolation_a, group = d$income )
## 
##  Descriptive statistics by group 
## group: 1 low
##    vars  n mean   sd median trimmed  mad min  max range skew kurtosis  se
## X1    1 45 1.98 0.69   1.75    1.94 0.74   1 3.25  2.25 0.45       -1 0.1
## ------------------------------------------------------------ 
## group: 2 middle
##    vars   n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 173 1.73 0.73    1.5    1.64 0.74   1 3.5   2.5 0.71    -0.69 0.06
## ------------------------------------------------------------ 
## group: 3 high
##    vars  n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 97 1.49 0.56   1.25    1.41 0.37   1 3.5   2.5 1.32     1.29 0.06
## ------------------------------------------------------------ 
## group: prefer not to say
##    vars  n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 50 1.65 0.75   1.38    1.55 0.56   1 3.5   2.5 0.89    -0.52 0.11
# also use histograms to examine your continuous variable
hist(d$isolation_a)

# REMEMBER your test's level of POWER is determined by your SMALLEST subsample

5 Check Your Assumptions

5.1 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 two error)
  • Homogeneity of variance should be confirmed (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.

5.1.1 Check levels of IVs

# One-Way
table(d$income)
## 
##             1 low          2 middle            3 high prefer not to say 
##                45               173                97                50
## If cross_cases() doesn't work for you, then use xtabs() instead. Fill in the code below and remove the "#" to run. Then hashtag out the cross_cases() line above.

#xtabs(~ V1 + V2, data=d)


# 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
# We will create a new dataframe for the two-way analysis and call it d_twoway and remove the pet owning Ps.

d_oneway <- subset(d, income != "prefer not to say")
d_oneway$income <- droplevels(d_oneway$income)

# double-check any changes we made
cross_cases(d_oneway, income)
 #Total 
 income 
   1 low  45
   2 middle  173
   3 high  97
   #Total cases  315

5.1.2 Check homogeneity of variance

# 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(isolation_a~income, data = d_oneway)
## Levene's Test for Homogeneity of Variance (center = median)
##        Df F value  Pr(>F)   
## group   2   6.129 0.00245 **
##       312                   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

5.1.3 Check for outliers using Cook’s distance and Residuals VS Leverage plot

5.1.3.1 Run a Regression to get both outlier plots

# 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.

# One-Way
reg_model <- lm(isolation_a~income, data = d_oneway) 

5.1.3.2 Check for outliers (One-Way)

# Cook's distance
plot(reg_model, 4)

# Residuals VS Leverage
plot(reg_model, 5)

5.2 Issues with My Data

Our cell sizes are very unbalanced between the income group levels. A small sample size for one of the levels of our variable limits our power and increases our Type 2 error rate.

Levene’s test was significant for our three-level income type variable with the one-way ANOVA. We are ignoring this and continuing with the analysis anyway for this class.

We identified and removed a single outlier for the One-Way ANOVA.

6 Run an ANOVA

# One-Way
aov_model <- aov_ez(data = d_oneway,
                    id = "X",
                    between = c("income"),
                    dv = "isolation_a",
                    anova_table = list(es = "pes"))
## Contrasts set to contr.sum for the following variables: income

7 View Output

# One-Way
nice(aov_model)
## Anova Table (Type 3 tests)
## 
## Response: isolation_a
##   Effect     df  MSE        F  pes p.value
## 1 income 2, 312 0.46 8.41 *** .051   <.001
## ---
## 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

8 Visualize Results

# One-Way
afex_plot(aov_model, x = "income")

9 Run Posthoc Tests (One-Way)

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="income", adjust="sidak")
##  income   emmean     SE  df lower.CL upper.CL
##  1 low      1.98 0.1010 312     1.74     2.22
##  2 middle   1.73 0.0515 312     1.61     1.85
##  3 high     1.49 0.0688 312     1.33     1.66
## 
## Confidence level used: 0.95 
## Conf-level adjustment: sidak method for 3 estimates
pairs(emmeans(aov_model, specs="income", adjust="sidak"))
##  contrast          estimate     SE  df t.ratio p.value
##  1 low - 2 middle     0.247 0.1130 312   2.176  0.0770
##  1 low - 3 high       0.483 0.1220 312   3.954  0.0003
##  2 middle - 3 high    0.236 0.0859 312   2.752  0.0172
## 
## P value adjustment: tukey method for comparing a family of 3 estimates

```

10 Write Up Results

10.1 One-Way ANOVA

To test our hypothesis that there will be a significant difference in people’s level of isolation based on the income level (low, middle, high), we used a one-way ANOVA. Our data was slightly unbalanced, with more people who are middle class participating in our survey (n = 173) than those who are low class (n = 45) or high class (n = 97). 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 signifcant Levene’s test (p = .007) also indicates that our data violates the assumption of homogeneity of variance. This suggests that there is an increased chance of Type one error. We continued with our analysis for the purpose of this class.

We found a significant effect of pet type, F(2, 312) = 4.13, p <.001, ηp2 = .047 (A small effect size; Cohen, 1988). Posthoc tests using Sidak’s adjustment revealed that participants who are low income (M = 1.98 , SE = .1020) reported more isolation than those who are middle class (M = 1.73, SE = .0522) but less isolation than those who are high class(M = 1.49, SE = .0697); participants who own are low class reported the highest amount of isolation overall (see Figure 1 for a comparison).

References

Cohen J. (1988). Statistical Power Analysis for the Behavioral Sciences. New York, NY: Routledge Academic.