1 Loading Libraries

library(psych) # for the describe() command
library(car) # for the vif() command
## Loading required package: carData
## 
## Attaching package: 'car'
## The following object is masked from 'package:psych':
## 
##     logit
library(sjPlot) # to visualize our results
## #refugeeswelcome

2 Importing Data

# import the dataset you cleaned previously
# this will be the dataset you'll use throughout the rest of the semester
# use EAMMi2 data
d <- read.csv(file="Data/eammi2_clean.csv", header=T)

set.seed(110)
d$fake <- (rnorm(n=nrow(d))-d$efficacy)*d$swb
d$fake <- d$fake+(d$fake*rnorm(n=nrow(d)))

3 State Your Hypothesis

We hypothesize that self-efficacy (measured by the GSE), need to belong (measured by the NBS), and fake data (a fake variable generated for this lab) will significantly predict subjective well-being (measured by the SWLS).

4 Check Your Variables

# you only need to check the variables you're using in the current analysis
# although 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':    3166 obs. of  7 variables:
##  $ ResponseId: chr  "R_BJN3bQqi1zUMid3" "R_2TGbiBXmAtxywsD" "R_12G7bIqN2wB2N65" "R_39pldNoon8CePfP" ...
##  $ gender    : chr  "f" "m" "m" "f" ...
##  $ race_rc   : chr  "white" "white" "white" "other" ...
##  $ swb       : num  4.33 4.17 1.83 5.17 3.67 ...
##  $ belong    : num  2.8 4.2 3.6 4 3.4 4.2 3.9 3.6 2.9 2.5 ...
##  $ efficacy  : num  3.4 3.4 2.2 2.8 3 2.4 2.3 3 3 3.7 ...
##  $ fake      : num  -30.78 4.09 -3.81 -19.12 -16.99 ...
cont <- na.omit(subset(d, select=c(swb,belong,efficacy,fake)))
cont$belong <- scale(cont$belong, center=T, scale=T)
cont$efficacy <- scale(cont$efficacy, center=T, scale=T)
cont$fake <- scale(cont$fake, center=T, scale=T)

# you can use the describe() command on an entire dataframe (d) or just on a single variable
describe(cont)
##          vars    n mean   sd median trimmed  mad   min  max range  skew
## swb         1 3166 4.47 1.32   4.67    4.53 1.48  1.00 7.00  6.00 -0.36
## belong      2 3166 0.00 1.00   0.11    0.03 0.98 -3.19 2.92  6.11 -0.26
## efficacy    3 3166 0.00 1.00  -0.06    0.01 1.00 -4.54 1.96  6.50 -0.24
## fake        4 3166 0.00 1.00   0.15    0.07 0.82 -5.18 3.84  9.02 -0.89
##          kurtosis   se
## swb         -0.45 0.02
## belong      -0.12 0.02
## efficacy     0.44 0.02
## fake         2.17 0.02
# also use histograms to examine your continuous variables
hist(cont$belong)

hist(cont$efficacy)

hist(cont$fake)

hist(cont$swb)

# last, use scatterplots to examine your continuous variables together
plot(cont$efficacy, cont$swb)

plot(cont$efficacy, cont$belong)

plot(cont$efficacy, cont$fake)

plot(cont$belong, cont$swb)

plot(cont$fake, cont$swb)

plot(cont$belong, cont$fake)

5 View Your Correlations

corr_output_m <- corr.test(cont)
corr_output_m
## Call:corr.test(x = cont)
## Correlation matrix 
##            swb belong efficacy  fake
## swb       1.00  -0.14     0.39 -0.26
## belong   -0.14   1.00    -0.26  0.06
## efficacy  0.39  -0.26     1.00 -0.19
## fake     -0.26   0.06    -0.19  1.00
## Sample Size 
## [1] 3166
## Probability values (Entries above the diagonal are adjusted for multiple tests.) 
##          swb belong efficacy fake
## swb        0      0        0    0
## belong     0      0        0    0
## efficacy   0      0        0    0
## fake       0      0        0    0
## 
##  To see confidence intervals of the correlations, print with the short=FALSE option

6 Run a Multiple Linear Regression

# use this commented out section only if you need to remove outliers
# to drop a single outlier, remove the # at the beginning of the line and use this code ((cont or d or whichever data set you are refering to))(change next line as well depending on needs - line 84):
# cont$row_id <- 1:nrow(cont)
# cont <- subset(cont, row_id!=c(1970))

# to drop multiple outliers, remove the # at the beginning of the line and use this code:
# d <- subset(d, row_id!=c(1108) & row_id!=c(602))

# use the lm() command to run the regression
# dependent/outcome variable on the left, independent/predictor variables on the right
reg_model <- lm(swb ~ belong + efficacy + fake, data = cont)

7 Check Your Assumptions

7.1 Multiple Linear Regression Assumptions

  • Observations should be independent
  • Number of cases should be adequate (N ≥ 80 + 8m, where m is the number of IVs)
  • Independent variables should not be too correlated (aka multicollinearity)
  • Variables should be continuous and normally distributed
  • Outliers should be identified and removed
  • Relationship between the variables should be linear
  • Residuals should be normal and have constant variance

7.2 Count Number of Cases

For your homework, if you don’t have the required number of cases you’ll need to drop one of your independent variables. Reach out to me and we can figure out the best way to proceed!

needed <- 80 + 8*3
nrow(cont) >= needed
## [1] TRUE

7.3 Check multicollinearity

  • Higher values indicate more multicollinearity
  • Cutoff is usually 5

For your homework, you will need to discuss multicollinearity and any high values, but you don’t have to drop any variables.

vif(reg_model)
##   belong efficacy     fake 
## 1.073156 1.107768 1.036399

7.4 Check linearity with Residuals vs Fitted plot

This plot (below) shows the residuals for each case and the fitted line. The red line is the average residual for the specified point of the dependent variable. If the assumption of linearity is met, the red line should be horizontal. This indicates that the residuals average to around zero. You can see that for this lab, the plot shows some non-linearity because there are more datapoints below the regression line than here are above it. Thus, there are some negative residuals that don’t have positive residuals to cancel them out. However, a bit of deviation is okay – just like with skewness and kurtosis, there’s a range that we can work in before non-normality or non-linearity becomes a critical issue. For some examples of good Residuals vs Fitted plot and ones that show serious errors, check out this page.

For your homework, you’ll simply need to generate this plot and talk about how your plot compares to the good and problematic plots linked to above. Is it closer to the ‘good’ plots or one of the ‘bad’ plots? This is going to be a judgement call, and that’s okay! In practice, you’ll always be making these judgement calls as part of a team, so this assignment is just about getting experience with it, not making the perfect call.

plot(reg_model, 1)

7.5 Check for outliers using Cook’s distance and a Residuals vs Leverage plot

The plots below both address leverage, or how much each data point is able to influence the regression line. Outliers are points that have undue influence on the regression line, the way that Bill Gates entering the room has an undue influence on the mean income.

The first plot, Cook’s distance, is a visualization of a score called (you guessed it) Cook’s distance, calculated for each case (aka row or participant) in the dataframe. Cook’s distance tells us how much the regression would change if the point was removed. The second plot also includes the residuals in the examination of leverage. The standardized residuals are on the y-axis and leverage is on the x-axis; this shows us which points have high residuals (are far from the regression line) and high leverage. Points that have large residuals and high leverage are especially worrisome, because they are far from the regression line but are also exerting a large influence on it.

For your homework, you’ll simply need to generate these plots, assess Cook’s distance in your dataset, and then identify any potential cases that are prominent outliers. Since we have some cutoffs, that makes this process is a bit less subjective than some of the other assessments we’ve done here, which is a nice change!

# Cook's distance
plot(reg_model, 4)

# Residuals vs Leverage
plot(reg_model, 5)

7.6 Check homogeneity of variance in a Scale-Location plot

This plot is similar to the one’s we’ve seen, but it shows us the standardized residuals across the range of the regression line. Because the residuals are standarized, large residuals (whether positive or negative) are at the top of the plot, while small residuals (whether positive or negative) are at the bottom of the plot. If the assumption of homogeneity of variance (also called homoscedasticity) is met, the red line should be mostly horizontal. If it deviates from the mean line, that means that the variance is smaller or larger at that point of the regression line.

Once again, you can check out this page for some other examples of this type of plot. (Notice that the Scale-Location plot is the third in the grids.) Our Scale-Location plot has some issues! We also still have our influential points indicated; this time, they’re in the top right corner, indicating that they have large residuals (are vary from the regression line).

For your homework, you’ll simply need to generate this plot and talk about how your plot compares to the ones pictured. Is it closer to the ‘good’ plots or one of the ‘bad’ plots? Again, this is a judgement call! It’s okay if feel uncertain, and you won’t be penalized for that.

plot(reg_model, 3)

7.6.1 Lab Only

We can use the residual plot below to see the variance issues with our ‘fake’ variable.

library(broom)
library(ggplot2)
## 
## Attaching package: 'ggplot2'
## The following objects are masked from 'package:psych':
## 
##     %+%, alpha
model.diag.metrics <- augment(reg_model)

ggplot(model.diag.metrics, aes(x = swb, y = fake)) +
  geom_point() +
  stat_smooth(method = lm, se = FALSE) +
  geom_segment(aes(xend = swb, yend = .fitted), color = "red", size = 0.3)
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## `geom_smooth()` using formula = 'y ~ x'

7.7 Check normality of residuals with a Q-Q plot

This plot is a bit new. It’s called a Q-Q plot and shows the standardized residuals plotted against a normal distribution. If our variables are perfectly normal, the points will fit on the dashed line perfectly. This page shows how different types of non-normality appear on a Q-Q plot.

It’s normal for Q-Q plots show a bit of deviation at the ends, and ours shows some deviation in the top right corner. It doesn’t perfectly fit any of the provided images, but it suggests some negative/right skew, which fits what we saw with the describe() command earlier.

This page shows some examples that help us put our Q-Q plot into context. Although it isn’t perfect, we don’t have any serious issues and are okay to proceed. For your homework, you’ll simply need to generate this plot and talk about how your plot compares to the ones pictured. Does it seem like any skew or kurtosis is indicated by your plot? Is it closer to the ‘good’/‘bad’ plots from the second link?

plot(reg_model, 2)

# Lab Only - not required for homework
qqnorm(d$swb)
qqline(d$swb)

qqnorm(d$belong)
qqline(d$belong)

qqnorm(d$efficacy)
qqline(d$efficacy)

qqnorm(d$fake)
qqline(d$fake)

7.8 Issues with My Data

Before interpreting our results, we assessed our variables to see if they met the assumptions for a multiple linear regression. We analyzed a Scale-Location plot and detected some issues with homogeneity of variance, as well as some issues with linearity in a Residuals vs Fitted plot. However, we did not detect any outliers (visually analyzing a Residuals vs Leverage plot) or any serious issues with the normality of our residuals (visually analyzing a Q-Q plot).

8 View Test Output

summary(reg_model)
## 
## Call:
## lm(formula = swb ~ belong + efficacy + fake, data = cont)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -4.0387 -0.8088  0.0793  0.8873  3.4071 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  4.47447    0.02112 211.867   <2e-16 ***
## belong      -0.05463    0.02188  -2.497   0.0126 *  
## efficacy     0.46049    0.02223  20.713   <2e-16 ***
## fake        -0.25210    0.02150 -11.724   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.188 on 3162 degrees of freedom
## Multiple R-squared:  0.1927, Adjusted R-squared:  0.192 
## F-statistic: 251.6 on 3 and 3162 DF,  p-value: < 2.2e-16
# note for section below: to type lowercase Beta below (ß) you need to hold down Alt key and type 225 on numeric keypad. If that doesn't work you should be able to copy/paste it from somewhere else

9 Write Up Results

To test our hypothesis that self-efficacy (measured by the GSE), need to belong (measured by the NBS), and a fake variable (created for this assignment) would significantly predict subjective well-being (measured by the SWLS), we used a multiple linear regression to model the relationship between the variables. We confirmed that our data met the assumptions of a linear regression, and although there were some issues with homogeneity of variance and linearity we continued with the analysis anyway.

Our model was statistically significant, Adj. R2 = .19, F(3,3162) = 251.6, p < .001. The relationship between self-efficacy and subjective wellbeing was positive and has a large effect size (per Cohen, 1988), while the relationships between our remaining predictors (need to belong and our fake variable) and our outcome (subjective wellbeing) were negative and had effect sizes that were small (fake variable) or trivial (need to belong). Full output from the regression model is reported in Table 1.

Table 1: Regression model of subjective wellbeing
  Subjective Wellbeing (SWLS)
Predictors Estimates SE CI p
Intercept 4.47 0.02 4.43 – 4.52 <0.001
Need to Belong (NBS) -0.05 0.02 -0.10 – -0.01 0.013
Self-Efficacy (GSE) 0.46 0.02 0.42 – 0.50 <0.001
Fake Variable (FKE) -0.25 0.02 -0.29 – -0.21 <0.001
Observations 3166
R2 / R2 adjusted 0.193 / 0.192


 

References

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