1 Loading Libraries

# install any packages you have not previously used, then comment them back out.

#install.packages("car")
#install.packages("effsize")

library(psych) # for the describe() command
library(car) # for the leveneTest() command
## Loading required package: carData
## 
## Attaching package: 'car'
## The following object is masked from 'package:psych':
## 
##     logit
library(effsize) # for the cohen.d() command
## 
## Attaching package: 'effsize'
## The following object is masked from 'package:psych':
## 
##     cohen.d

2 Importing Data

d <- read.csv(file="Data/projectdata.csv", header=T)

# For the HW, you will import the project dataset you cleaned previously
# This will be the dataset you'll use for HWs throughout the rest of the semester

3 State Your Hypothesis

We predict that Democrats will report significantly higher levels of subjective well-being than Republicans.

4 Check Your Variables

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

## Checking the Categorical variable (IV)

str(d)
## 'data.frame':    1616 obs. of  7 variables:
##  $ ResponseID: chr  "R_12G7bIqN2wB2N65" "R_2CfdmFw1NTliv4e" "R_24kJPxVOxMshN3Q" "R_3JmBijdH1z82QU2" ...
##  $ race_rc   : chr  "white" "white" "multiracial" "white" ...
##  $ party_rc  : chr  "apolitical" "democrat" "democrat" "apolitical" ...
##  $ pipwd     : num  2.33 3.53 3 3 3.13 ...
##  $ swb       : num  1.83 5.5 5 4.67 3 ...
##  $ support   : num  5.17 6.08 6 6 6 ...
##  $ stress    : num  4 2.4 2.9 3.5 2.5 3.5 4.4 2.8 1.8 3.6 ...
# if the categorical variable you're using is showing as a "chr" (character), you must change it to be a ** factor ** -- using the next line of code (as.factor)

 d$party_rc <- as.factor(d$party_rc)

str(d)
## 'data.frame':    1616 obs. of  7 variables:
##  $ ResponseID: chr  "R_12G7bIqN2wB2N65" "R_2CfdmFw1NTliv4e" "R_24kJPxVOxMshN3Q" "R_3JmBijdH1z82QU2" ...
##  $ race_rc   : chr  "white" "white" "multiracial" "white" ...
##  $ party_rc  : Factor w/ 4 levels "apolitical","democrat",..: 1 2 2 1 2 3 1 2 2 2 ...
##  $ pipwd     : num  2.33 3.53 3 3 3.13 ...
##  $ swb       : num  1.83 5.5 5 4.67 3 ...
##  $ support   : num  5.17 6.08 6 6 6 ...
##  $ stress    : num  4 2.4 2.9 3.5 2.5 3.5 4.4 2.8 1.8 3.6 ...
table(d$party_rc, useNA = "always")
## 
##  apolitical    democrat independent  republican        <NA> 
##         219         823         184         390           0
## Checking the Continuous variable (DV)

# you can use the describe() command on an entire dataframe (d) or just on a single variable within your dataframe -- which we will do here

describe(d$swb)
##    vars    n mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 1616 4.33 1.35    4.5    4.38 1.48   1   7     6 -0.3     -0.5 0.03
# also use a histogram to visualize your continuous variable

hist(d$swb)

# use the describeBy() command to view the means and standard deviations by group
# it's very similar to the describe() command but splits the dataframe according to the 'group' variable

describeBy(d$swb, group=d$party_rc)
## 
##  Descriptive statistics by group 
## group: apolitical
##    vars   n mean   sd median trimmed  mad min max range  skew kurtosis   se
## X1    1 219 4.15 1.37   4.33    4.17 1.48   1   7     6 -0.12    -0.72 0.09
## ------------------------------------------------------------ 
## group: democrat
##    vars   n mean   sd median trimmed  mad min max range  skew kurtosis   se
## X1    1 823 4.19 1.36   4.33    4.23 1.48   1   7     6 -0.23    -0.59 0.05
## ------------------------------------------------------------ 
## group: independent
##    vars   n mean   sd median trimmed  mad min max range  skew kurtosis  se
## X1    1 184 4.29 1.41   4.33    4.36 1.73   1   7     6 -0.35    -0.48 0.1
## ------------------------------------------------------------ 
## group: republican
##    vars   n mean   sd median trimmed  mad min max range  skew kurtosis   se
## X1    1 390 4.72 1.22   4.83    4.79 1.24   1   7     6 -0.48    -0.05 0.06
# lastly, use a boxplot to examine your chosen continuous and categorical variables together

boxplot(d$swb~d$party_rc)

5 Check Your Assumptions

5.1 T-test Assumptions

  • IV must have two levels
  • Data values must be independent (independent t-test only)
  • Data obtained via a random sample
  • Dependent variable must be normally distributed
  • Variances of the two groups are approximately equal
# If the IV has more than 2 levels, you must DROP any additional levels in order to meet the first assumption of a t-test.

## NOTE: This is a FOUR STEP process!

 d<- subset(d, party_rc != "apolitical") # use subset() to remove all participants from the additional level

table(d$party_rc, useNA = "always") # verify that now there are ZERO participants in the additional level
## 
##  apolitical    democrat independent  republican        <NA> 
##           0         823         184         390           0
 d$party_rc<- droplevels(d$party_rc) # use droplevels() to drop the empty factor

table(d$party_rc, useNA = "always") # verify that now the entire factor level is removed 
## 
##    democrat independent  republican        <NA> 
##         823         184         390           0
#round two:
d<- subset(d, party_rc != "independent") # use subset() to remove all participants from the additional level

table(d$party_rc, useNA = "always") # verify that now there are ZERO participants in the additional level
## 
##    democrat independent  republican        <NA> 
##         823           0         390           0
 d$party_rc<- droplevels(d$party_rc) # use droplevels() to drop the empty factor

table(d$party_rc, useNA = "always") # verify that now the entire factor level is removed 
## 
##   democrat republican       <NA> 
##        823        390          0
## Repeat ALL THE STEPS ABOVE if your IV has more levels that need to be DROPPED. Copy the 4 lines of code, and replace the level name in the subset() command.

5.2 Testing Homogeneity of Variance with Levene’s Test

We can test whether the variances of our two groups are equal using Levene’s test. The NULL hypothesis is that the variance between the two groups is equal, which is the result we WANT. So when running Levene’s test we’re hoping for a NON-SIGNIFICANT result!

# use the leveneTest() command from the car package to test homogeneity of variance
# it uses the same 'formula' setup that we'll use for our t-test: formula is y~x, where y is our DV and x is our IV

leveneTest(swb~party_rc, data =d)
## Levene's Test for Homogeneity of Variance (center = median)
##         Df F value   Pr(>F)   
## group    1  9.1298 0.002568 **
##       1211                    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Levene’s test revealed that our data has significantly different variances between the two comparison groups, democrats and republicans, on their levels of subjective well-being.

When running a t-test, we can account for heterogeneity in our variance by using the Welch’s t-test, which does not have the same assumption about variance as the Student’s t-test (the general default type of t-test in statistics). R defaults to using Welch’s t-test so this doesn’t require any changes on our part! Even if your data has no issues with homogeneity of variance, you’ll still use Welch’s t-test – it handles the potential issues around variance well and there are no real downsides. We’re using Levene’s test here to get into the habit of checking the homogeneity of our variance, even if we already have the solution for any potential problems.

5.3 Issues with My Data

My independent variable has more than two levels. To proceed with this analysis, I will drop the apolitical and independent participants from my sample. I will make a note to discuss this issue in my Methods section write-up and in my discussion section as a limitation of my study.

My data also has an issue regarding homogeneity of variance, as Levene’s test was significant. To accommodate for this heterogeneity of variance, I will use Welch’s t-test instead of Student’s t-test in my analysis.

6 Run a T-test

# Very simple! we use the same formula of y~x, where y is our DV and x is our IV

t_output <- t.test(d$swb~d$party_rc)  # t_output will now show in your Global Environment

7 View Test Output

t_output
## 
##  Welch Two Sample t-test
## 
## data:  d$swb by d$party_rc
## t = -6.7619, df = 839.35, p-value = 2.549e-11
## alternative hypothesis: true difference in means between group democrat and group republican is not equal to 0
## 95 percent confidence interval:
##  -0.6804683 -0.3743001
## sample estimates:
##   mean in group democrat mean in group republican 
##                 4.194411                 4.721795

8 Calculate Cohen’s d - Effect Size

# once again, we use the same formula, y~x, to calculate cohen's d

# We **only** calculate effect size if the test is SIG!

d_output <- cohen.d(d$swb~d$party_rc)  # d_output will now show in your Global Environment

9 View Effect Size

d_output
## 
## Cohen's d
## 
## d estimate: -0.4006987 (small)
## 95 percent confidence interval:
##      lower      upper 
## -0.5223594 -0.2790380
## Remember to always take the ABSOLAUTE VALUE of the effect size value (i.e., it will never be negative)

10 Write Up Results

To test our hypothesis that Democrats in our sample would report significantly higher levels of subjective well-being than Republicans, we used an independent samples t-test. This required us to drop our apolitical and independent party aligned participants from our sample, as we are limited to a two-group comparison when using this test. We tested the homogeneity of variance with Levene’s test and found signs of heterogeneity (p < .001). This suggests that there is an increased chance of Type 1 error. To correct for this issue, we used Welch’s t-test, which does not assume homogeneity of variance. Our data met all other assumptions of an independent samples t-test.

Contrary to what we predicted, we found that Republicans (M = 4.72, SD = 1.22) reported significantly higher levels of subjective well-being than Democrats (M = 4.19, SD = 1.36); t(839.35) = -6.76, p <0.001 (see Figure 1). The effect size was calculated using Cohen’s d, with a value of 0.40 (small effect; Cohen, 1988).

References

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