1 Loading Libraries

#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 select columns from data: columns(mtcars, mpg, vs:carb)
## 
## Attaching package: 'maditr'
## The following object is masked from 'package:base':
## 
##     sort_by
## 
## 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'

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 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: I predict that there will be a significant effect of political party on people’s exploitativeness.

4 Check Your Variables

# 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':    3141 obs. of  8 variables:
##  $ ResponseId: chr  "R_BJN3bQqi1zUMid3" "R_2TGbiBXmAtxywsD" "R_12G7bIqN2wB2N65" "R_39pldNoon8CePfP" ...
##  $ npi       : num  0.6923 0.1538 0.0769 0.0769 0.7692 ...
##  $ exploit   : num  2 3.67 4.33 1.67 4 ...
##  $ stress    : num  3.3 3.3 4 3.2 3.1 3.5 3.3 2.4 2.9 2.7 ...
##  $ swb       : num  4.33 4.17 1.83 5.17 3.67 ...
##  $ party_rc  : chr  "democrat" "independent" "apolitical" "apolitical" ...
##  $ edu       : chr  "2 Currently in college" "5 Completed Bachelors Degree" "2 Currently in college" "2 Currently in college" ...
##  $ 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$CATVARIABLE <- as.factor(d$CATVARIABLE) 
d$pet <- as.factor(d$exploit)
d$race <- as.factor(d$exploit) 
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$party_rc)
## 
##  apolitical    democrat independent  republican 
##         438        1596         326         781
d$party_rc[d$party_rc == "democrat"] <- "non-republican"
d$party_rc[d$party_rc == "independent"] <- "non-republican"
d$party_rc[d$party_rc == "apolitical"] <- "non-republican"
d$party_rc[d$party_rc == "republican"] <- "republican"
table(d$party_rc)
## 
## non-republican     republican 
##           2360            781
d$party_rc <- as.factor(d$party_rc)

# check that all our categorical variables of interest are now factors
str(d)
## 'data.frame':    3141 obs. of  10 variables:
##  $ ResponseId: chr  "R_BJN3bQqi1zUMid3" "R_2TGbiBXmAtxywsD" "R_12G7bIqN2wB2N65" "R_39pldNoon8CePfP" ...
##  $ npi       : num  0.6923 0.1538 0.0769 0.0769 0.7692 ...
##  $ exploit   : num  2 3.67 4.33 1.67 4 ...
##  $ stress    : num  3.3 3.3 4 3.2 3.1 3.5 3.3 2.4 2.9 2.7 ...
##  $ swb       : num  4.33 4.17 1.83 5.17 3.67 ...
##  $ party_rc  : Factor w/ 2 levels "non-republican",..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ edu       : chr  "2 Currently in college" "5 Completed Bachelors Degree" "2 Currently in college" "2 Currently in college" ...
##  $ row_id    : Factor w/ 3141 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
##  $ pet       : Factor w/ 19 levels "1","1.33333333333333",..: 4 9 11 3 10 2 14 1 8 1 ...
##  $ race      : Factor w/ 19 levels "1","1.33333333333333",..: 4 9 11 3 10 2 14 1 8 1 ...
# check our DV skew and kurtosis
describe(d$exploit)
##    vars    n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 3141 2.39 1.37      2    2.21 1.48   1   7     6 0.94     0.36 0.02
# we'll use the describeBy() command to view our DV's skew and kurtosis across our IVs' levels
describeBy(d$exploit, group = d$exploit)
## 
##  Descriptive statistics by group 
## group: 1
##    vars   n mean sd median trimmed mad min max range skew kurtosis se
## X1    1 910    1  0      1       1   0   1   1     0  NaN      NaN  0
## ------------------------------------------------------------ 
## group: 1.33333333333333
##    vars   n mean sd median trimmed mad  min  max range skew kurtosis se
## X1    1 183 1.33  0   1.33    1.33   0 1.33 1.33     0  NaN      NaN  0
## ------------------------------------------------------------ 
## group: 1.66666666666667
##    vars   n mean sd median trimmed mad  min  max range skew kurtosis se
## X1    1 229 1.67  0   1.67    1.67   0 1.67 1.67     0  NaN      NaN  0
## ------------------------------------------------------------ 
## group: 2
##    vars   n mean sd median trimmed mad min max range skew kurtosis se
## X1    1 379    2  0      2       2   0   2   2     0  NaN      NaN  0
## ------------------------------------------------------------ 
## group: 2.33333333333333
##    vars   n mean sd median trimmed mad  min  max range skew kurtosis se
## X1    1 193 2.33  0   2.33    2.33   0 2.33 2.33     0  NaN      NaN  0
## ------------------------------------------------------------ 
## group: 2.66666666666667
##    vars   n mean sd median trimmed mad  min  max range skew kurtosis se
## X1    1 160 2.67  0   2.67    2.67   0 2.67 2.67     0  NaN      NaN  0
## ------------------------------------------------------------ 
## group: 3
##    vars   n mean sd median trimmed mad min max range skew kurtosis se
## X1    1 272    3  0      3       3   0   3   3     0  NaN      NaN  0
## ------------------------------------------------------------ 
## group: 3.33333333333333
##    vars   n mean sd median trimmed mad  min  max range skew kurtosis se
## X1    1 154 3.33  0   3.33    3.33   0 3.33 3.33     0  NaN      NaN  0
## ------------------------------------------------------------ 
## group: 3.66666666666667
##    vars   n mean sd median trimmed mad  min  max range skew kurtosis se
## X1    1 131 3.67  0   3.67    3.67   0 3.67 3.67     0  NaN      NaN  0
## ------------------------------------------------------------ 
## group: 4
##    vars   n mean sd median trimmed mad min max range skew kurtosis se
## X1    1 172    4  0      4       4   0   4   4     0  NaN      NaN  0
## ------------------------------------------------------------ 
## group: 4.33333333333333
##    vars  n mean sd median trimmed mad  min  max range skew kurtosis se
## X1    1 87 4.33  0   4.33    4.33   0 4.33 4.33     0  NaN      NaN  0
## ------------------------------------------------------------ 
## group: 4.66666666666667
##    vars  n mean sd median trimmed mad  min  max range skew kurtosis se
## X1    1 77 4.67  0   4.67    4.67   0 4.67 4.67     0  NaN      NaN  0
## ------------------------------------------------------------ 
## group: 5
##    vars  n mean sd median trimmed mad min max range skew kurtosis se
## X1    1 76    5  0      5       5   0   5   5     0  NaN      NaN  0
## ------------------------------------------------------------ 
## group: 5.33333333333333
##    vars  n mean sd median trimmed mad  min  max range skew kurtosis se
## X1    1 32 5.33  0   5.33    5.33   0 5.33 5.33     0  NaN      NaN  0
## ------------------------------------------------------------ 
## group: 5.66666666666667
##    vars  n mean sd median trimmed mad  min  max range skew kurtosis se
## X1    1 23 5.67  0   5.67    5.67   0 5.67 5.67     0  NaN      NaN  0
## ------------------------------------------------------------ 
## group: 6
##    vars  n mean sd median trimmed mad min max range skew kurtosis se
## X1    1 24    6  0      6       6   0   6   6     0  NaN      NaN  0
## ------------------------------------------------------------ 
## group: 6.33333333333333
##    vars n mean sd median trimmed mad  min  max range skew kurtosis se
## X1    1 6 6.33  0   6.33    6.33   0 6.33 6.33     0  NaN      NaN  0
## ------------------------------------------------------------ 
## group: 6.66666666666667
##    vars n mean sd median trimmed mad  min  max range skew kurtosis se
## X1    1 2 6.67  0   6.67    6.67   0 6.67 6.67     0  NaN      NaN  0
## ------------------------------------------------------------ 
## group: 7
##    vars  n mean sd median trimmed mad min max range skew kurtosis se
## X1    1 31    7  0      7       7   0   7   7     0  NaN      NaN  0
describeBy(d$exploit, group = d$party_rc)
## 
##  Descriptive statistics by group 
## group: non-republican
##    vars    n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 2360 2.37 1.38      2    2.18 1.48   1   7     6 0.99     0.46 0.03
## ------------------------------------------------------------ 
## group: republican
##    vars   n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 781 2.44 1.35      2    2.29 1.48   1   7     6  0.8     0.05 0.05
# also use histograms to examine your continuous variable
hist(d$exploit)

# and cross_cases() to examine your categorical variables' cell count
cross_cases(d, exploit, party_rc)
 party_rc 
 non-republican   republican 
 exploit 
   1  694 216
   1.33333333333333  147 36
   1.66666666666667  181 48
   2  272 107
   2.33333333333333  149 44
   2.66666666666667  115 45
   3  200 72
   3.33333333333333  123 31
   3.66666666666667  93 38
   4  126 46
   4.33333333333333  56 31
   4.66666666666667  48 29
   5  60 16
   5.33333333333333  25 7
   5.66666666666667  21 2
   6  19 5
   6.33333333333333  5 1
   6.66666666666667  2
   7  24 7
   #Total cases  2360 781
# 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 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 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.

5.1.1 Check levels of IVs

# One-Way
table(d$exploit)
## 
##                1 1.33333333333333 1.66666666666667                2 
##              910              183              229              379 
## 2.33333333333333 2.66666666666667                3 3.33333333333333 
##              193              160              272              154 
## 3.66666666666667                4 4.33333333333333 4.66666666666667 
##              131              172               87               77 
##                5 5.33333333333333 5.66666666666667                6 
##               76               32               23               24 
## 6.33333333333333 6.66666666666667                7 
##                6                2               31
# Two-Way
#cross_cases(d, exploit, party_rc)


# 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, exploit != "independent")
#d_tw$exploit <- droplevels(d_tw$exploit)

# double-check any changes we made
#cross_cases(d_tw, exploit, party_rc)

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(exploit~party_rc, data = d)
## Levene's Test for Homogeneity of Variance (center = median)
##         Df F value Pr(>F)
## group    1  0.0245 0.8756
##       3139
# Two-Way
#leveneTest(companionship~pet*poc, data = d_tw)

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

5.1.3.1 Run a Regression to get these 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.
reg_model <- lm(exploit~party_rc, data = d) #for One-Way
#reg_model2 <- lm(companionship~pet*poc, data = d_tw) #for Two-Way

5.1.3.2 Check for outliers (One-Way)

# Cook's distance
plot(reg_model, 4)

# Residuals VS Leverage
plot(reg_model, 5)

5.1.3.3 Check for outliers (Two-Way)

# Cook's distance
#plot(reg_model2, 4)

# Residuals vs Leverage
#plot(reg_model2, 5)

5.2 Issues with My Data

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 not significant for my two-level political party type variable.

I identified and removed any outliers.

[UPDATE this section in your HW.]

6 Run an ANOVA

contrasts(d$party_rc) <- contr.treatment(levels(d$party_rc))
# One-Way
aov_model <- aov_ez(data = d,
                    id = "row_id",
                    between = c("party_rc"),
                    dv = "exploit",
                    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: exploit
##     Effect      df  MSE    F   pes p.value
## 1 party_rc 1, 3137 1.88 1.77 <.001    .184
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '+' 0.1 ' ' 1
str(d$exploit)
##  num [1:3139] 2 3.67 4.33 1.67 4 ...
str(d$party_rc)
##  Factor w/ 2 levels "non-republican",..: 1 1 1 1 1 1 1 1 1 1 ...
##  - attr(*, "contrasts")= num [1:2, 1] 0 1
##   ..- attr(*, "dimnames")=List of 2
##   .. ..$ : chr [1:2] "non-republican" "republican"
##   .. ..$ : chr "republican"
aov_model <- aov_ez(data = d,
                    id = "row_id",
                    between = "party_rc",
                    dv = "exploit",
                    anova_table = list(es = "pes"))
## Contrasts set to contr.sum for the following variables: party_rc
# Two-Way
#aov_model2 <- aov_ez(data = d_tw,
                 #   id = "X",
                   # between = c("pet","poc"),
                  #  dv = "companionship",
                  #  anova_table = list(es = "pes"))

7 View Output

nice(aov_model)
## Anova Table (Type 3 tests)
## 
## Response: exploit
##     Effect      df  MSE    F   pes p.value
## 1 party_rc 1, 3137 1.88 1.77 <.001    .184
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '+' 0.1 ' ' 1
#nice(aov_model2)

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

8 Visualize Results

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

# Two-Way
#afex_plot(aov_model2, x = "party_rc", trace = "exploit")
#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

9 Run Posthoc Tests (One-Way)

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="party_rc", adjust="tukey")
## Note: adjust = "tukey" was changed to "sidak"
## because "tukey" is only appropriate for one set of pairwise comparisons
##  party_rc       emmean     SE   df lower.CL upper.CL
##  non-republican   2.37 0.0283 3137     2.30     2.43
##  republican       2.44 0.0492 3137     2.33     2.55
## 
## Confidence level used: 0.95 
## Conf-level adjustment: sidak method for 2 estimates
pairs(emmeans(aov_model, specs="party_rc", adjust="tukey"))
##  contrast                      estimate     SE   df t.ratio p.value
##  (non-republican) - republican  -0.0754 0.0567 3137  -1.329  0.1840

10 Run Posthoc Tests (Two-Way)

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_model2, specs="pet", adjust="tukey")
#pairs(emmeans(aov_model, specs="pet", adjust="tukey"))

# 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="pet", adjust="tukey")
#pairs(emmeans(aov_model2, specs="pet", adjust="tukey"))
 
# IV1 and IV2 interaction effect
#emmeans(aov_model2, specs="poc", adjust="tukey")
#pairs(emmeans(aov_model2, specs="poc", adjust="tukey"))

#emmeans(aov_model2, specs="pet", by="poc", adjust="sidak")
#pairs(emmeans(aov_model2, specs="pet", by="poc", adjust="sidak"))

#emmeans(aov_model2, specs="poc", by="pet", adjust="sidak")
#pairs(emmeans(aov_model2, specs="poc", by="pet", adjust="sidak"))

11 Write Up Results

11.1 One-Way ANOVA

To test my hypothesis that there would be a significant effect of type of political party on people’s exploitativeness, I used a one-way ANOVA. My data was balanced. I identified any outliers following visual analysis of Cook’s Distance and Residuals VS Leverage plots. A Levene’s test was not significant (p = 0.8756) also indicates that my data does not violate the assumption of homogeneity of variance. This suggests that there is not an increased chance of Type I error.

I did not find a significant effect of political party, F(2, 3137) = -1.329, p > .001, ηp2 = 0.1840 (large effect size; Cohen, 1988).

11.2 Two-Way ANOVA

References

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