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 select columns from data: columns(mtcars, mpg, vs:carb)
## 
## 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 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 needing to belong based on the type of education level they have comppleted. (High school diploma or less, and NO College, Completed bachelor’s degree, completed some grad degree).

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':    3160 obs. of  8 variables:
##  $ ResponseID: chr  "R_BJN3bQqi1zUMid3" "R_2TGbiBXmAtxywsD" "R_12G7bIqN2wB2N65" "R_39pldNoon8CePfP" ...
##  $ gender    : chr  "f" "m" "m" "f" ...
##  $ edu       : chr  "2 Currently in college" "5 Completed Bachelors Degree" "2 Currently in college" "2 Currently in college" ...
##  $ socmeduse : int  47 23 34 35 37 13 37 43 37 29 ...
##  $ belong    : num  2.8 4.2 3.6 4 3.4 4.2 3.9 3.6 2.9 2.5 ...
##  $ swb       : num  4.33 4.17 1.83 5.17 3.67 ...
##  $ idea      : num  3.75 3.88 3.75 3.75 3.5 ...
##  $ 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$edu <- as.factor(d$edu) 
d$row_id <- as.factor(d$row_id)



d <- subset(d, edu != "2 Currently in college") # use subset() to remove all participants from the additional level

table(d$edu, useNA = "always") # verify that now there are ZERO participants in the additional level
## 
##      1 High school diploma or less, and NO COLLEGE 
##                                                 59 
##                             2 Currently in college 
##                                                  0 
## 3 Completed some college, but no longer in college 
##                                                 35 
##                   4 Complete 2 year College degree 
##                                                181 
##                       5 Completed Bachelors Degree 
##                                                139 
##                  6 Currently in graduate education 
##                                                136 
##                   7 Completed some graduate degree 
##                                                 58 
##                                               <NA> 
##                                                  0
 d$edu <- droplevels(d$edu) # use droplevels() to drop the empty factor

table(d$edu, useNA = "always") # verify that now the entire factor level is removed 
## 
##      1 High school diploma or less, and NO COLLEGE 
##                                                 59 
## 3 Completed some college, but no longer in college 
##                                                 35 
##                   4 Complete 2 year College degree 
##                                                181 
##                       5 Completed Bachelors Degree 
##                                                139 
##                  6 Currently in graduate education 
##                                                136 
##                   7 Completed some graduate degree 
##                                                 58 
##                                               <NA> 
##                                                  0
d <- subset(d, edu != "3 Completed some college, but no longer in college") # use subset() to remove all participants from the additional level

table(d$edu, useNA = "always") # verify that now there are ZERO participants in the additional level
## 
##      1 High school diploma or less, and NO COLLEGE 
##                                                 59 
## 3 Completed some college, but no longer in college 
##                                                  0 
##                   4 Complete 2 year College degree 
##                                                181 
##                       5 Completed Bachelors Degree 
##                                                139 
##                  6 Currently in graduate education 
##                                                136 
##                   7 Completed some graduate degree 
##                                                 58 
##                                               <NA> 
##                                                  0
 d$edu <- droplevels(d$edu) # use droplevels() to drop the empty factor

table(d$edu, useNA = "always") # verify that now the entire factor level is removed 
## 
## 1 High school diploma or less, and NO COLLEGE 
##                                            59 
##              4 Complete 2 year College degree 
##                                           181 
##                  5 Completed Bachelors Degree 
##                                           139 
##             6 Currently in graduate education 
##                                           136 
##              7 Completed some graduate degree 
##                                            58 
##                                          <NA> 
##                                             0
d <- subset(d, edu != "4 Complete 2 year College degree") # use subset() to remove all participants from the additional level

table(d$edu, useNA = "always") # verify that now there are ZERO participants in the additional level
## 
## 1 High school diploma or less, and NO COLLEGE 
##                                            59 
##              4 Complete 2 year College degree 
##                                             0 
##                  5 Completed Bachelors Degree 
##                                           139 
##             6 Currently in graduate education 
##                                           136 
##              7 Completed some graduate degree 
##                                            58 
##                                          <NA> 
##                                             0
 d$edu <- droplevels(d$edu) # use droplevels() to drop the empty factor

table(d$edu, useNA = "always") # verify that now the entire factor level is removed 
## 
## 1 High school diploma or less, and NO COLLEGE 
##                                            59 
##                  5 Completed Bachelors Degree 
##                                           139 
##             6 Currently in graduate education 
##                                           136 
##              7 Completed some graduate degree 
##                                            58 
##                                          <NA> 
##                                             0
d <- subset(d, edu != "6 Currently in graduate education") # use subset() to remove all participants from the additional level

table(d$edu, useNA = "always") # verify that now there are ZERO participants in the additional level
## 
## 1 High school diploma or less, and NO COLLEGE 
##                                            59 
##                  5 Completed Bachelors Degree 
##                                           139 
##             6 Currently in graduate education 
##                                             0 
##              7 Completed some graduate degree 
##                                            58 
##                                          <NA> 
##                                             0
 d$edu <- droplevels(d$edu) # use droplevels() to drop the empty factor

table(d$edu, useNA = "always") # verify that now the entire factor level is removed 
## 
## 1 High school diploma or less, and NO COLLEGE 
##                                            59 
##                  5 Completed Bachelors Degree 
##                                           139 
##              7 Completed some graduate degree 
##                                            58 
##                                          <NA> 
##                                             0
table(d$edu)
## 
## 1 High school diploma or less, and NO COLLEGE 
##                                            59 
##                  5 Completed Bachelors Degree 
##                                           139 
##              7 Completed some graduate degree 
##                                            58
d$edu <- as.factor(d$edu)

# check that all our categorical variables of interest are now factors
str(d)
## 'data.frame':    256 obs. of  8 variables:
##  $ ResponseID: chr  "R_2TGbiBXmAtxywsD" "R_2Quh0h3wxTjZjKP" "R_1gTNDGWsqikPuEX" "R_1KlHNd0KK9iCNJn" ...
##  $ gender    : chr  "m" "f" "f" "m" ...
##  $ edu       : Factor w/ 3 levels "1 High school diploma or less, and NO COLLEGE",..: 2 2 2 3 2 3 2 2 2 2 ...
##  $ socmeduse : int  23 37 26 26 18 37 23 42 42 28 ...
##  $ belong    : num  4.2 3.9 3 4.1 1.5 3.3 3.9 4.2 4.2 3.1 ...
##  $ swb       : num  4.17 3.67 5.33 5.17 5.67 ...
##  $ idea      : num  3.88 3.5 3.62 2.88 1.88 ...
##  $ row_id    : Factor w/ 3160 levels "1","2","3","4",..: 2 7 16 17 31 56 57 58 59 60 ...
# check our DV skew and kurtosis
describe(d$belong)
##    vars   n mean   sd median trimmed  mad min max range  skew kurtosis   se
## X1    1 256 3.12 0.65    3.1    3.12 0.74 1.5 4.6   3.1 -0.02    -0.61 0.04
# we'll use the describeBy() command to view our DV's skew and kurtosis across our IVs' levels
describeBy(d$belong, group = d$edu)
## 
##  Descriptive statistics by group 
## group: 1 High school diploma or less, and NO COLLEGE
##    vars  n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 59 2.97 0.66    2.9    2.96 0.74 1.6 4.6     3 0.12    -0.52 0.09
## ------------------------------------------------------------ 
## group: 5 Completed Bachelors Degree
##    vars   n mean   sd median trimmed  mad min max range  skew kurtosis   se
## X1    1 139  3.2 0.63    3.1    3.21 0.74 1.5 4.3   2.8 -0.08    -0.73 0.05
## ------------------------------------------------------------ 
## group: 7 Completed some graduate degree
##    vars  n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 58 3.09 0.65      3     3.1 0.59 1.5 4.5     3 0.02    -0.54 0.08
# also use histograms to examine your continuous variable
hist(d$belong)

# 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$edu)
## 
## 1 High school diploma or less, and NO COLLEGE 
##                                            59 
##                  5 Completed Bachelors Degree 
##                                           139 
##              7 Completed some graduate degree 
##                                            58
# 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.

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(belong~edu, data = d)
## Levene's Test for Homogeneity of Variance (center = median)
##        Df F value Pr(>F)
## group   2  0.0262 0.9742
##       253

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 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(belong~edu, data = d) #for One-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.2 Issues with My Data

Our cell sizes are soemwhat unbalanced between the education level groups. There were larger sample sizes from some levels (completed bachelor’s degree) and smaller sizes for others (high school diploma or less). While this could slight affect the power, it is not a major concern at this time.

Levene’s test was not significant for our one-way ANOVA.

We did not identify or remove any outliers for the One-Way ANOVA.

[UPDATE this section in your HW.]

6 Run an ANOVA

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

7 View Output

nice(aov_model)
## Anova Table (Type 3 tests)
## 
## Response: belong
##   Effect     df  MSE      F  pes p.value
## 1    edu 2, 253 0.41 2.73 + .021    .067
## ---
## 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 = "edu")

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="edu", adjust="sidak")
##  edu                                           emmean     SE  df lower.CL
##  1 High school diploma or less, and NO COLLEGE   2.97 0.0837 253     2.77
##  5 Completed Bachelors Degree                    3.20 0.0545 253     3.07
##  7 Completed some graduate degree                3.09 0.0844 253     2.89
##  upper.CL
##      3.17
##      3.33
##      3.29
## 
## Confidence level used: 0.95 
## Conf-level adjustment: sidak method for 3 estimates
pairs(emmeans(aov_model, specs="edu", adjust="sidak"))
##  contrast                                                                        
##  1 High school diploma or less, and NO COLLEGE - 5 Completed Bachelors Degree    
##  1 High school diploma or less, and NO COLLEGE - 7 Completed some graduate degree
##  5 Completed Bachelors Degree - 7 Completed some graduate degree                 
##  estimate     SE  df t.ratio p.value
##    -0.229 0.0998 253  -2.297  0.0581
##    -0.120 0.1190 253  -1.011  0.5706
##     0.109 0.1000 253   1.087  0.5230
## 
## P value adjustment: tukey method for comparing a family of 3 estimates

NOTE: Accidently ran this when I should not have. (posthoc)


# Write Up Results
## One-Way ANOVA

To test our hypothesis that there will be a significant difference in people's need tp belong based on their education level, we used a one-way ANOVA. Our data was somewhat unbalanced, with many more people who have completed a bacehlor's degree participating in our survey (*n* = 139) than who had completed some graduate degree (*n* = 58) or those who had a high school diploma or less and NO college (*n* = 59). While this may reduce statistical power, it is not a major concern.We did not identify or remove any outliers visual analysis of Cook's Distance and Residuals VS Leverage plots. A non- significant Levene's test (*p* = .974) also indicating that the asusmption of homogeneity of varianace was met. We continued with our analysis for the purpose of this class. 

We did not find a significant significant effect of education on need to belong, *F*(2, 253) = 2.73, *p* <.067, *η~p~^2^* = .021 (small effect size; Cohen, 1988). ; participants who have completed a bachelor's degree reported the highest amount of need to belong overall (see Figure 1 for a comparison).

<img src="ANOVA-HW-for-EC_files/figure-html/unnamed-chunk-12-1.png" width="672" />





References

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