correlation: Loading Libraries

library(psych) # for the describe() command and the corr.test() command
library(apaTables) # to create our correlation table
library(kableExtra) # to create our correlation table

Importing Data

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

Correlation: State Your Hypothesis

I predict that efficacy and belonging will be positively correlated.

Correlation: 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':    3182 obs. of  6 variables:
##  $ efficacy          : num  3.4 3.4 2.2 2.8 3 2.4 2.3 3 3 3.7 ...
##  $ belong            : int  4 4 2 4 4 3 4 4 4 3 ...
##  $ marriageimportance: int  2 3 2 1 2 3 4 3 4 2 ...
##  $ race_rc           : chr  "white" "white" "white" "other" ...
##  $ politicalviews    : num  2.5 2.5 5 8 4.5 8 4 1.5 5.5 6 ...
##  $ income            : int  3 3 1 1 6 1 2 3 7 1 ...
# since we're focusing on our continuous variables, we're going to subset them into their own dataframe. this will make some stuff we're doing later easier.

cont <- subset(d, select=c(belong, efficacy))

# you can use the describe() command on an entire dataframe (d) or just on a single variable (d$pss)
describe(cont)
##          vars    n mean   sd median trimmed  mad min max range  skew kurtosis
## belong      1 3178 3.61 1.00    4.0    3.68 1.48   1   5     4 -0.62     0.04
## efficacy    2 3176 3.13 0.45    3.1    3.13 0.44   1   4     3 -0.29     0.63
##            se
## belong   0.02
## efficacy 0.01
# also use histograms to examine your continuous variables
hist(d$belong)

hist(d$efficacy)

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

Correlation: Check Your Assumptions

Pearson’s Correlation Coefficient Assumptions

  • Should have two measurements for each participant
  • Variables should be continuous and normally distributed
  • Outliers should be identified and removed
  • Relationship between the variables should be linear

Checking for Outliers

Note: You are not required to screen out outliers or take any action based on what you see here. This is something you will check and then discuss in your write-up.

d$belong_std <- scale(d$belong, center=T, scale=T)
hist(d$belong_std)

sum(d$belong_std < -3 | d$belong_std > 3)
## [1] NA
d$efficacy_std <- scale(d$efficacy, center=T, scale=T)
hist(d$efficacy_std)

sum(d$efficacy_std < -3 | d$efficacy_std > 3)
## [1] NA

Correlation: Issues with My Data

All of my variables meet all of the assumptions of Pearson’s correlation coefficient.

Correlation: Create a Correlation Matrix

corr_output_m <- corr.test(cont)

Correlation: View Test Output

corr_output_m
## Call:corr.test(x = cont)
## Correlation matrix 
##          belong efficacy
## belong     1.00     0.31
## efficacy   0.31     1.00
## Sample Size 
##          belong efficacy
## belong     3178     3174
## efficacy   3174     3176
## Probability values (Entries above the diagonal are adjusted for multiple tests.) 
##          belong efficacy
## belong        0        0
## efficacy      0        0
## 
##  To see confidence intervals of the correlations, print with the short=FALSE option

Correlation: Write Up Results

To test our hypothesis that efficacy and belonging would be correlated with one another, I calculated a series of Pearson’s correlation coefficients. Most of my data met the assumptions of the test, with all variables meeting the standards of normality and no outliers. There is a positive and statistically significant correlation between the variables “belong” and “efficacy” with a correlation coefficient of 0.31. The effect size can be considered medium (r=0.3 is medium; Cohen, 1988). This means that there is a noticeable but not strong relationship between the variables.

Efficacy and Belonging rise and fall together, which can be seen by the correlation coefficients reported in Table 1.

Table 1: Means, standard deviations, and correlations with confidence intervals
Variable M SD 1
Efficacy (1995 Generalized Self-Efficacy Scale) 3.61 1.00
Belonging (2013 Construct validity of the Need to Belong Scale) 3.13 0.45 .31**
[.28, .34]
Note:
M and SD are used to represent mean and standard deviation, respectively. Values in square brackets indicate the 95% confidence interval. The confidence interval is a plausible range of population correlations that could have caused the sample correlation.
* indicates p < .05
** indicates p < .01.

References

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

regression: Loading Libraries

library(psych) # for the describe() command
library(broom) # for the augment() command
library(ggplot2) # to visualize our results
## 
## Attaching package: 'ggplot2'
## The following objects are masked from 'package:psych':
## 
##     %+%, alpha

regression: State Your Hypothesis

We hypothesize that self-efficacy (measured by the GSE) will significantly predict belonging (measured by the NTBS), and that the relationship will be positive.

regression: 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':    3182 obs. of  8 variables:
##  $ efficacy          : num  3.4 3.4 2.2 2.8 3 2.4 2.3 3 3 3.7 ...
##  $ belong            : int  4 4 2 4 4 3 4 4 4 3 ...
##  $ marriageimportance: int  2 3 2 1 2 3 4 3 4 2 ...
##  $ race_rc           : chr  "white" "white" "white" "other" ...
##  $ politicalviews    : num  2.5 2.5 5 8 4.5 8 4 1.5 5.5 6 ...
##  $ income            : int  3 3 1 1 6 1 2 3 7 1 ...
##  $ belong_std        : num [1:3182, 1] 0.389 0.389 -1.613 0.389 0.389 ...
##   ..- attr(*, "scaled:center")= num 3.61
##   ..- attr(*, "scaled:scale")= num 0.999
##  $ efficacy_std      : num [1:3182, 1] 0.611 0.611 -2.057 -0.723 -0.278 ...
##   ..- attr(*, "scaled:center")= num 3.13
##   ..- attr(*, "scaled:scale")= num 0.45
# you can use the describe() command on an entire dataframe (d) or just on a single variable
describe(d)
##                    vars    n mean   sd median trimmed  mad   min  max range
## efficacy              1 3176 3.13 0.45   3.10    3.13 0.44  1.00 4.00  3.00
## belong                2 3178 3.61 1.00   4.00    3.68 1.48  1.00 5.00  4.00
## marriageimportance    3 3172 3.63 1.11   4.00    3.72 1.48  1.00 5.00  4.00
## race_rc*              4 2880 4.95 1.75   6.00    5.28 0.00  1.00 6.00  5.00
## politicalviews        5 3163 4.14 2.05   4.00    4.01 2.22  1.00 8.00  7.00
## income                6 3157 3.54 2.30   3.00    3.37 2.97  1.00 9.00  8.00
## belong_std            7 3178 0.00 1.00   0.39    0.07 1.48 -2.61 1.39  4.00
## efficacy_std          8 3176 0.00 1.00  -0.06    0.01 0.99 -4.72 1.95  6.67
##                     skew kurtosis   se
## efficacy           -0.29     0.63 0.01
## belong             -0.62     0.04 0.02
## marriageimportance -0.59    -0.35 0.02
## race_rc*           -1.25    -0.14 0.03
## politicalviews      0.40    -0.93 0.04
## income              0.47    -1.12 0.04
## belong_std         -0.62     0.04 0.02
## efficacy_std       -0.29     0.63 0.02
# also use histograms to examine your continuous variables
hist(d$efficacy)

hist(d$belong)

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

regression: Run a Simple Regression

# to calculate standardized coefficients, we have to standardize our IV
d$efficacy_std <- scale(d$efficacy, center=T, scale=T)
hist(d$efficacy_std)

# use the lm() command to run the regression
# dependent/outcome variable on the left, idependent/predictor variable on the right
reg_model <- lm(belong ~ efficacy_std, data = d)

regression: Check Your Assumptions

Simple Regression Assumptions

  • Should have two measurements for each participant
  • 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 note: we will not be evaluating whether our data meets these assumptions in this lab/homework – we’ll come back to them next week when we talk about multiple linear regression

Create plots and view residuals

model.diag.metrics <- augment(reg_model)

ggplot(model.diag.metrics, aes(x = efficacy_std, y = belong)) +
  geom_point() +
  stat_smooth(method = lm, se = FALSE) +
  geom_segment(aes(xend = efficacy_std, 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'

Check linearity with Residuals vs Fitted plot

My plot is closer to the ‘good’ plots than the ‘bad’ plots, because there seems to be linearity.

plot(reg_model, 1)

regression: Check for outliers

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. Ideally, we want all points to have the same influence on the regression line, although we accept that there will be some variability. The cutoff for a high Cook’s distance score is .5 (not .05, which is our cutoff for statistical significance). For our data, some points do exert more influence than others but they’re generally equal, and none of them are close to the cutoff.

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. Point 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. The red line indicates the average residual across points with the same amount of leverage. As usual, we want this line to stay as close to the mean line (or the zero line) as possible.

Because the leverage in our plot is low, part of it actually cut off! If you check the first set of plots on this page (note that Residuals vs Leverage is the fourth in the grid) you can see there are curved red lines in the corners of the Residuals vs Leverage plots. This is the .5 cutoff for Cook’s distance, and so any points appearing past these lines is a serious outlier that needs to be removed. On this page you can also see Residuals vs Leverage plots with severe deviations from the mean line, which makes our deviations appear much less serious.

Our data doesn’t have any severe outliers. 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!

My response: Data points 786, 3134, and 1675 have large cook’s distances. Luckily, the outliers were not too influential.

# Cook's distance
plot(reg_model, 4)

# Residuals vs Leverage
plot(reg_model, 5)

regression: Issues with My Data

Before interpreting our results, we assessed our variables to see if they met the assumptions for a simple linear regression. Analysis of a Residuals vs Fitted plot suggested that there is some minor non-linearity, but not enough to violate the assumption of linearity. We also checked Cook’s distance and a Residuals vs Leverage plot to detect outliers. One case had a large residuals and above-average leverage but was below the recommended cutoff for Cook’s distance.

regression: View Test Output

summary(reg_model)
## 
## Call:
## lm(formula = belong ~ efficacy_std, data = d)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -3.2096 -0.5949  0.2002  0.6100  2.7027 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   3.61205    0.01688  213.92   <2e-16 ***
## efficacy_std  0.30721    0.01689   18.19   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.9513 on 3172 degrees of freedom
##   (8 observations deleted due to missingness)
## Multiple R-squared:  0.09446,    Adjusted R-squared:  0.09418 
## F-statistic: 330.9 on 1 and 3172 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

regression: Write Up Results

To test my hypothesis that efficacy (measured by the GSE) will significantly predict subjective belonging (measured by the NTBS), and that the relationship will be positive, I used a simple linear regression to model the relationship between the variables. I confirmed that my data met the assumptions of a linear regression, checking the linearity of the relationship using a Residuals vs Fitted plot and checking for outliers using Cook’s distance and a Residuals vs Leverage plot.

As predicted, I found that efficacy significantly predicted belonging, Adj. R2 = .094, F(3172) = 330.9, p < .001. The relationship between self-efficacy and belongingwas positive, ß = .30, t(3172) = 18.19, p < .001 (refer to Figure 1). According to Cohen (1988), this constitutes a medium effect size (around .30).

References

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