1 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

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

2 Importing Data

# import the dataset you cleaned previously
# this will be the dataset you'll use throughout the rest of the semester
# use ARC data downloaded previous for lab
d <- read.csv(file="Data/Data Cleaning & Basic Statistics HW/eammi2_test (2).csv", header=T)

3 Corrilation: State Your Hypothesis

I predict that Subjective well being measured by the subjective well being scale BBC, percieved social support (measured by the PSSS), Need to belong (measured by the NTB), and Social Media Use (SMUIS) will all be correlated with each other.

4 Corrilation: 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  7 variables:
##  $ ResponseId: chr  "R_BJN3bQqi1zUMid3" "R_2TGbiBXmAtxywsD" "R_12G7bIqN2wB2N65" "R_39pldNoon8CePfP" ...
##  $ sex       : chr  "f" "m" "m" "f" ...
##  $ income    : chr  "20,000-39,999" "20,000-39,999" "rather not say" "rather not say" ...
##  $ swb       : num  4.33 4.17 1.83 5.17 3.67 ...
##  $ belong    : num  3.4 3.4 3.6 3.6 3.2 3.4 3.5 3.2 3.5 2.7 ...
##  $ support   : num  6 6.75 5.17 5.58 6 ...
##  $ SocMedia  : num  4.27 2.09 3.09 3.18 3.36 ...
# 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(swb, support, belong, SocMedia))

# 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
## swb         1 3178 4.47 1.32   4.67    4.53 1.48   1   7     6 -0.36    -0.46
## support     2 3176 5.53 1.13   5.75    5.65 0.99   1   7     6 -1.10     1.39
## belong      3 3175 3.31 0.49   3.30    3.33 0.44   1   5     4 -0.33     0.64
## SocMedia    4 3175 3.13 0.78   3.18    3.16 0.67   1   5     4 -0.31     0.26
##            se
## swb      0.02
## support  0.02
## belong   0.01
## SocMedia 0.01
# our fake variable has high kurtosis, which I'll ignore. you don't need to discuss univariate normality in the results write-ups for the labs/homework, but you will need to discuss it in your final manuscript

# also use histograms to examine your continuous variables
hist(d$swb)

# last, use scatterplots to examine your continuous variables together
hist(d$support)

hist(d$SocMedia)

plot(d$swb, d$support)

plot(d$swb, d$belong)

plot(d$swb, d$SocMedia)

plot(d$support, d$belong)

plot(d$support, d$SocMedia)

plot(d$belong, d$SocMedia)

5 Corrilation: Check Your Assumptions

5.1 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

5.1.1 Corrilation: 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$swb_std <- scale(d$swb, center=T, scale=T)

hist(d$swb_std)

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

5.2 Corrilation: Issues with My Data

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

6 Corrilation: Create a Correlation Matrix

corr_output_m <- corr.test(cont)

7 Corrilation: View Test Output

corr_output_m
## Call:corr.test(x = cont)
## Correlation matrix 
##            swb support belong SocMedia
## swb       1.00    0.47  -0.05     0.11
## support   0.47    1.00   0.08     0.21
## belong   -0.05    0.08   1.00     0.28
## SocMedia  0.11    0.21   0.28     1.00
## Sample Size 
##           swb support belong SocMedia
## swb      3178    3173   3173     3173
## support  3173    3176   3171     3171
## belong   3173    3171   3175     3170
## SocMedia 3173    3171   3170     3175
## Probability values (Entries above the diagonal are adjusted for multiple tests.) 
##           swb support belong SocMedia
## swb      0.00       0   0.01        0
## support  0.00       0   0.00        0
## belong   0.01       0   0.00        0
## SocMedia 0.00       0   0.00        0
## 
##  To see confidence intervals of the correlations, print with the short=FALSE option

8 Corrilation: Write Up Results

To test our hypothesis that subjective well being measured by the subjective well being scale (SWB), percieved social support, measured by the Multidimensional Scale of Perceived Social Support (MSPSS), Need to belong (measured by the NTB Scale), and a Social Media Use Self-report survey data will all be correlated with each other, we calculated a series of Pearson’s correlation coefficients. Most of uur data met the assumptions of the test, with all variables meeting the standards of normality and no outliers. One variable, fakeness, did have outliers and non-linear relationships with the other variables, and so any significant results involving that variable should be evaluated carefully.

As predicted, we found that all three variables were significantly correlated (all ps < .001). The effect sizes of all correlations were large (rs > .5; Cohen, 1988). This test also supported our second hypothesis, that self-esteem would be lower in participants who are higher in stress or who report more symptoms of depression, as can be seen by the correlation coefficients reported in Table 1.

## [1] 11
## [1] 11
Table 1: Means, standard deviations, and correlations with confidence intervals
Variable M SD 1 2 3
Subjective well-being (SWB) 4.47 1.32
perceived Social Support (MSPSS) 5.53 1.13 .47**
[.45, .50]
Need to Belong (NTB)
3.31 0.49 -.05** .08**
[-.08, -.01] [.04, .11]
Social Media use (self report survey)
3.13 0.78 .11** .21** .28**
[.07, .14] [.17, .24] [.24, .31]
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.

9 Simple Regression: State Your Hypothesis

We hypothesize that self-efficacy (measured by the GSE) will significantly predict subjective well-being (measured by the SWLS), and that the relationship will be positive.

10 Simple 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:
##  $ ResponseId: chr  "R_BJN3bQqi1zUMid3" "R_2TGbiBXmAtxywsD" "R_12G7bIqN2wB2N65" "R_39pldNoon8CePfP" ...
##  $ sex       : chr  "f" "m" "m" "f" ...
##  $ income    : chr  "20,000-39,999" "20,000-39,999" "rather not say" "rather not say" ...
##  $ swb       : num  4.33 4.17 1.83 5.17 3.67 ...
##  $ belong    : num  3.4 3.4 3.6 3.6 3.2 3.4 3.5 3.2 3.5 2.7 ...
##  $ support   : num  6 6.75 5.17 5.58 6 ...
##  $ SocMedia  : num  4.27 2.09 3.09 3.18 3.36 ...
##  $ swb_std   : num [1:3182, 1] -0.104 -0.23 -1.994 0.526 -0.608 ...
##   ..- attr(*, "scaled:center")= num 4.47
##   ..- attr(*, "scaled:scale")= num 1.32
# 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
## ResponseId*    1 3182 1591.50 918.71 1591.50 1591.50 1179.41  1.00 3182.00
## sex*           2 3178    1.28   0.49    1.00    1.21    0.00  1.00    3.00
## income*        3 3157    5.52   2.86    6.00    5.65    2.97  1.00    9.00
## swb            4 3178    4.47   1.32    4.67    4.53    1.48  1.00    7.00
## belong         5 3175    3.31   0.49    3.30    3.33    0.44  1.00    5.00
## support        6 3176    5.53   1.13    5.75    5.65    0.99  1.00    7.00
## SocMedia       7 3175    3.13   0.78    3.18    3.16    0.67  1.00    5.00
## swb_std        8 3178    0.00   1.00    0.15    0.04    1.12 -2.62    1.91
##               range  skew kurtosis    se
## ResponseId* 3181.00  0.00    -1.20 16.29
## sex*           2.00  1.40     0.88  0.01
## income*        8.00 -0.27    -1.42  0.05
## swb            6.00 -0.36    -0.46  0.02
## belong         4.00 -0.33     0.64  0.01
## support        6.00 -1.10     1.39  0.02
## SocMedia       4.00 -0.31     0.26  0.01
## swb_std        4.54 -0.36    -0.46  0.02
# also use histograms to examine your continuous variables
hist(d$swb)

hist(d$support)

hist(d$belong)

hist(d$SocMedia)

# last, use scatterplots to examine your continuous variables together

plot(d$swb, d$support, xlab = "swb", ylab = "support")

plot(d$swb, d$belong, xlab = "swb", ylab = "belong")

plot(d$swb, d$SocMedia, xlab = "swb", ylab = "SocMedia")

# Repeat for other variable combinations

plot(d$support, d$belong, xlab = "support", ylab = "belong")

plot(d$support, d$SocMedia, xlab = "support", ylab = "SocMedia")

plot(d$support, d$swb, xlab = "support", ylab = "swb")

# Repeat for other variable combinations

plot(d$belong, d$swb, xlab = "belong", ylab = "swb")

plot(d$belong, d$SocMedia, xlab = "belong", ylab = "SocMedia")

plot(d$belong, d$swb, xlab = "belong", ylab = "Swb")

plot(d$belong, d$swb, xlab = "belong", ylab = "swb")

plot(d$belong, d$SocMedia, xlab = "belong", ylab = "SocMedia")

plot(d$belong, d$swb, xlab = "belong", ylab = "swb")

11 Simple Regression:Run a Simple Regression

# to calculate standardized coefficients, we have to standardize our IV


d$swb_std <- scale(d$swb, center=T, scale=T)

hist(d$swb_std)

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

hist(d$belong_std)

d$SocMedia_std <- scale(d$SocMedia, center=T, scale=T)

hist(d$SocMedia_std)

d$support_std <- scale(d$support, center=T, scale=T)

hist(d$support_std)

# use the lm() command to run the regression
# dependent/outcome variable on the left, idependent/predictor variable on the right

reg_model <- lm(swb ~ swb_std, data = d)

reg_model <- lm(belong ~ SocMedia_std, data = d)
reg_model <- lm(swb ~ belong_std, data = d)
reg_model <- lm(support ~ belong_std, data = d)
reg_model <- lm(SocMedia ~ belong_std, data = d)

reg_model <- lm(swb ~ swb_std, data = d)
reg_model <- lm(swb ~ belong_std, data = d)
reg_model <- lm(SocMedia ~ belong_std, data = d)

12 Simple Regression: Check Your Assumptions

12.1 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

12.2 Create plots and view residuals

model.diag.metrics <- augment(reg_model)

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

12.3 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. I’ve included the images in our video and talk about them more in-depth there. But to summarize quickly, you can see the first case has a plot in which the red line sticks pretty closely to the zero line, while the other cases show some serious deviation. Ours is much closer to the ‘good’ plot than it is to the ‘serious issues’ plots. So we’ll consider our data okay and proceed with our analysis. Obviously, this is quite subjective. I’ll talk a bit about why this is in the video, but the key takeaway is that these evaluations are closely tied to the context of our sample, our data, and what we’re studying. It’s almost always a judgement call.

You’ll notice in the bottom right corner, there are some points with numbers included: these are cases or participants (indicated by row number) who have the most influence on the regression line (and so they might outliers).We’ll talk more about outliers in the next section.

To summarize: our plot suggests there is some minor non-linearity. 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)

12.4 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!

# Cook's distance
plot(reg_model, 4)

# Residuals vs Leverage
plot(reg_model, 5)

12.5 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.

13 Simple Regression: View Test Output

summary(reg_model)
## 
## Call:
## lm(formula = SocMedia ~ belong_std, data = d)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -2.47445 -0.44259  0.01584  0.48107  2.35228 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  3.13142    0.01332  235.08   <2e-16 ***
## belong_std   0.21532    0.01332   16.16   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.75 on 3168 degrees of freedom
##   (12 observations deleted due to missingness)
## Multiple R-squared:  0.07615,    Adjusted R-squared:  0.07586 
## F-statistic: 261.1 on 1 and 3168 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

14 Simple Regression: Write Up Results

To test our hypothesis that self-efficacy (measured by the GSE) will significantly predict subjective well-being (measured by the SWLS), and that the relationship will be positive, we used a simple linear regression to model the relationship between the variables. We confirmed that our 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. Note: we are skipping the assumptions of normality and homogeneity of variance for this assignment.

As predicted, we found that self-efficacy significantly predicted subjective wellbeing, Adj. R2 = .16, F(1,3164) = 584.1, p < .001. The relationship between self-efficacy and subjective wellbeing was positive, ß = .52, t(3164) = 24.17, p < .001 (refer to Figure 1). According to Cohen (1988), this constitutes a large effect size (> .50).

References

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