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
library(expss) # for the cross_cases() command
library(car) # for the leveneTest() command
library(afex) # to run the ANOVA 
library(ggbeeswarm) # to run plot results
library(emmeans) # for posthoc tests

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)

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

3 One-Way ANOVA

3.1 State Your Hypothesis

We predict that there will be a significant difference in people’s level of loneliness based on the location they live in (urban, town, village).

3.2 Check Your Variables

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

str(d)
## 'data.frame':    694 obs. of  8 variables:
##  $ X          : int  520 2814 3146 3295 717 6056 4753 5365 2044 1965 ...
##  $ mhealth    : chr  "none or NA" "none or NA" "none or NA" "none or NA" ...
##  $ urban_rural: chr  "town" "town" "town" "town" ...
##  $ covid_pos  : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ big5_ext   : num  2 2.67 4.67 4.33 1.67 ...
##  $ isolation_c: num  1 1 1 1 1 1 1 1 1 1 ...
##  $ phq        : num  1.56 1.44 1.11 1.33 1.44 ...
##  $ 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$urban_rural <- as.factor(d$urban_rural) 
d$row_id <- as.factor(d$row_id)


# check that our categorical variables of interest are now factors
str(d)
## 'data.frame':    694 obs. of  8 variables:
##  $ X          : int  520 2814 3146 3295 717 6056 4753 5365 2044 1965 ...
##  $ mhealth    : chr  "none or NA" "none or NA" "none or NA" "none or NA" ...
##  $ urban_rural: Factor w/ 4 levels "city","isolated dwelling",..: 3 3 3 3 4 1 3 1 4 4 ...
##  $ covid_pos  : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ big5_ext   : num  2 2.67 4.67 4.33 1.67 ...
##  $ isolation_c: num  1 1 1 1 1 1 1 1 1 1 ...
##  $ phq        : num  1.56 1.44 1.11 1.33 1.44 ...
##  $ row_id     : Factor w/ 694 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
#check levels
table(d$urban_rural)
## 
##              city isolated dwelling              town           village 
##               170                16               297               211
# Our small number of participants living in isolated dwellings is going to affect our power.
# We will create a new dataframe and call it "d_anova" and remove the isolated dwelling Ps.

d_anova <- subset(d, urban_rural != "isolated dwelling")
d_anova$urban_rural <- droplevels(d_anova$urban_rural)

# check our DV skew and kurtosis
describe(d_anova$isolation_c)
##    vars   n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 678 2.27 0.81   2.25    2.28 1.11   1 3.5   2.5    0    -1.23 0.03
# we'll use the describeBy() command to view our DV's skew and kurtosis across our IVs' levels
describeBy(d_anova$isolation_c, group = d_anova$urban_rural)
## 
##  Descriptive statistics by group 
## group: city
##    vars   n mean   sd median trimmed  mad min max range  skew kurtosis   se
## X1    1 170 2.43 0.78    2.5    2.46 1.11   1 3.5   2.5 -0.22    -1.12 0.06
## ------------------------------------------------------------ 
## group: town
##    vars   n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 297 2.29 0.83   2.25    2.29 1.11   1 3.5   2.5 0.01    -1.31 0.05
## ------------------------------------------------------------ 
## group: village
##    vars   n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 211 2.13 0.78   2.25    2.11 1.11   1 3.5   2.5 0.16    -1.11 0.05
# also use histograms to examine your continuous variable
hist(d_anova$isolation_c)

3.3 Check Your Assumptions

3.3.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 II 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.

3.3.2 Check levels of IVs

table(d_anova$urban_rural)
## 
##    city    town village 
##     170     297     211
# REMEMBER your test's level of POWER is determined by your SMALLEST subsample

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

3.3.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))  # NOTE: Participant 1108 is not truly problamtic in the Lab, but we are going to removed them for demonstration.

# 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~x, where y is our DV, x is our IV

reg_model <- lm(isolation_c~urban_rural, data = d_anova) 

3.3.3.2 Check for outliers

# Cook's distance
plot(reg_model, 4)

# Residuals VS Leverage
plot(reg_model, 5)

# IF you find outliers, go back up to line 114 or 117 and remove it/them, then re-run the reg_model code

3.3.4 Check homogeneity of variance

# use the leveneTest() command from the car package to test homogeneity of variance
# uses the 'formula' setup: formula is y~x, where y is our DV and x is our IV 
leveneTest(isolation_c~urban_rural, data = d_anova)
## Levene's Test for Homogeneity of Variance (center = median)
##        Df F value Pr(>F)
## group   2  1.6077 0.2011
##       675

3.3.5 Issues with My Data

Our cell sizes were unbalanced between the location type group levels. A small sample size for one of the levels of our variable (isolated dwelling, n = 16) limits our power and increases our Type II error rate, therefore we dropped the isolated dwelling level to reduce Type II error rate.

Levene’s test was not significant for our three-level location type variable with the One-Way ANOVA.

We identified no outliers for the One-Way ANOVA.

3.4 Run a One-Way ANOVA

aov_model <- aov_ez(data = d_anova,
                    id = "X",
                    between = c("urban_rural"),
                    dv = "isolation_c",
                    anova_table = list(es = "pes" ))
## Contrasts set to contr.sum for the following variables: urban_rural

3.5 View One-Way Output

nice(aov_model)
## Anova Table (Type 3 tests)
## 
## Response: isolation_c
##        Effect     df  MSE       F  pes p.value
## 1 urban_rural 2, 675 0.65 6.44 ** .019    .002
## ---
## 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

3.6 Visualize One-Way Results

afex_plot(aov_model, x = "urban_rural")

3.7 Run One-Way Posthoc Tests

Remember: We ONLY run posthoc IF the ANOVA test is SIGNIFICANT! E.g., only run the posthoc tests on location type if there is a main effect for location type

emmeans(aov_model, specs="urban_rural")
##  urban_rural emmean     SE  df lower.CL upper.CL
##  city          2.43 0.0618 675     2.31     2.55
##  town          2.29 0.0467 675     2.20     2.38
##  village       2.13 0.0554 675     2.02     2.24
## 
## Confidence level used: 0.95
pairs(emmeans(aov_model, specs="urban_rural", adjust="tukey"))
##  contrast       estimate     SE  df t.ratio p.value
##  city - town       0.139 0.0775 675   1.800  0.1703
##  city - village    0.296 0.0830 675   3.568  0.0011
##  town - village    0.157 0.0725 675   2.161  0.0788
## 
## P value adjustment: tukey method for comparing a family of 3 estimates

3.8 Write Up One-Way ANOVA Results

To test our hypothesis that there will be a a significant difference in people’s level of felt companionship based on the location (city, town, village), we used a one-way ANOVA. Our data was relatively balanced, with a similar number of people who live in a city (n = 170), a town (n = 297), and a village (n = 211) participating in our survey (n = 678). We also identified no outliers following visual analysis of Cook’s Distance and Residuals vs Leverage plots. A non significant Levene’s test (p = 0.20 ) also indicates that our data meets the assumption of homogeneity of variance. As all assumptions for the ANOVA test were met, we thus continued with our analysis.

We found a significant effect of location, F(2, 675) = 6.44, p = 0.002, ηp2 = 0.019 (small effect; Cohen, 1988). Posthoc tests using Tukey’s HSD adjustment revealed that participants who live in a town (M = 2.29, SE = 0.05) reported more loneliness than those who live in a village (M = 2.13, SE = 0.06) but less companionship than those who own a rabbit (M = 2.43, SE = 0.06); participants who live in a city reported the highest amount of loneliness overall (see Figure 1 for a comparison).

References

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