This is our first lab when we are considering 2 dimensions and instead of calculating univariate statistics by groups (or factors) of other variable - we will measure their common relationships based on co-variance and correlation coefficients.
*Please be very careful when choosing the measure of correlation! In case of different measurument scales we have to recode one of the variables into weaker scale.
It would be nice to add some additional plots in the background. Feel free to add your own sections and use external packages also.
First let’s visualize our quantitative relationships using scatterplots.
You can also transform the skewed distribution of incomes using log:
We can add an estimated linear regression line:
## `geom_smooth()` using formula 'y ~ x'
We can finally see if there any differences between risk status:
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
## -- Attaching packages --------------------------------------- tidyverse 1.3.0 --
## <U+221A> tibble 3.1.0 <U+221A> purrr 0.3.4
## <U+221A> tidyr 1.1.3 <U+221A> stringr 1.4.0
## <U+221A> readr 1.4.0 <U+221A> forcats 0.5.1
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
## Loading required package: tools
## `geom_smooth()` using formula 'y ~ x'
We can also see more closely if there any differences between those two distributions adding their estimated density plots:
We can also put those plots together:
## `geom_smooth()` using formula 'y ~ x'
We can also see more closely if there any differences between those two distributions adding their estimated density plots:
##
## Attaching package: 'gridExtra'
## The following object is masked from 'package:dplyr':
##
## combine
Ok, let’s move to some calculations. In R, we can use the cor() function. It takes three arguments and the method: cor(x, y, method) For 2 quantitative data, with all assumptions met, we can calculate simple Pearson’s coefficient of linear correlation:
## [1] 0.574346
Ok, what about the percentage of the explained variability?
## [1] 0.3298734
So as we can see almost 33% of total log of incomes’ variability is explained by differences in age. The rest (67%) is probably explained by other factors.
The partial and semi-partial (also known as part) correlations are used to express the specific portion of variance explained by eliminating the effect of other variables when assessing the correlation between two variables.
Partial correlation holds constant one variable when computing the relations to others. Suppose we want to know the correlation between X and Y holding Z constant for both X and Y. That would be the partial correlation between X and Y controlling for Z.
Semipartial correlation holds Z constant for either X or Y, but not both, so if we wanted to control X for Z, we could compute the semipartial correlation between X and Y holding Z constant for X.
Suppose we want to know the correlation between the log of income and age controlling for years of employment. How highly correlated are these after controlling for tenure?
**There can be more than one control variable.
## Loading required package: MASS
##
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
##
## select
| estimate | p.value | statistic | n | gp | Method |
|---|---|---|---|---|---|
| 0.3194263 | 0 | 8.899323 | 700 | 1 | pearson |
How can we interpret the obtained partial correlation coefficient? What is the difference between that one and the semi-partial coefficient:
| estimate | p.value | statistic | n | gp | Method |
|---|---|---|---|---|---|
| 0.2203711 | 0 | 5.964597 | 700 | 1 | pearson |
For 2 different scales - like for example this pair of variables: income vs. education levels - we cannot use Pearson’s coefficient. The only possibility is to rank also incomes… and lose some more detailed information about them.
First, let’s see boxplots of income by education levels.
Now, let’s see Kendal’s coefficient of rank correlation (robust for ties).
## [1] 0.1577567
Let’s try to verify if there is a significant relationship between incomes and risk status. First, let’s take a look at the boxplot:
If you would like to compare 1 quantitative variable (income) and 1 dychotomous variable (default status - binary), then you can use point-biserial coefficient:
## Loading required package: msm
## Loading required package: polycor
## [1] 0.1352258
If you would like to check if there are any nonlinearities between 2 variables, the only possibility (beside transformations and linear analysis) is to calculate “eta” coefficient and compare it with the Pearson’s linear coefficient.
## [1] 0.6596682
## [1] 0.4787099
## [1] 0.2059989
We can also prepare the correlation matrix for all quantitative variables stored in our data frame. We can use ggcorr() function: ggcorr(df, method = c(“pairwise”, “pearson”), nbreaks = NULL, digits = 2, low = “#3B9AB2”, mid = “#EEEEEE”, high = “#F21A00”, geom = “tile”, label = FALSE, label_alpha = FALSE)
## Registered S3 method overwritten by 'GGally':
## method from
## +.gg ggplot2
## Warning in ggcorr(bank, nbreaks = 6, low = "steelblue", mid = "white", high =
## "darkred", : data in column(s) 'def', 'educ' are not numeric and were ignored
As you can see - the default correlation matrix is not the best idea for all measurement scales (including binary variable “default”).
That’s why now we can perform our bivariate analysis with ggpair with grouping.
Here is what we are about to calculate: - The correlation matrix between age, log_income, employ, address, debtinc, creddebt, and othdebt variable grouped by whether the person has a default status or not. - Plot the distribution of each variable by group - Display the scatter plot with the trend by group
Do you believe in the Afterlife? https://nationalpost.com/news/canada/millennials-do-you-believe-in-life-after-life A survey was conducted and a random sample of 1091 questionnaires is given in the form of the following contingency table:
## Believe
## Gender Yes No
## Female 435 375
## Male 147 134
Our task is to check if there is a significant relationship between the belief in the afterlife and gender. We can perform this procedure with the simple chi-square statistics and chosen qualitative correlation coefficient (two-way 2x2 table).
##
## Attaching package: 'psych'
## The following object is masked from 'package:ltm':
##
## factor.scores
## The following object is masked from 'package:polycor':
##
## polyserial
## The following objects are masked from 'package:ggplot2':
##
## %+%, alpha
##
## Pearson's Chi-squared test with Yates' continuity correction
##
## data: dane
## X-squared = 0.11103, df = 1, p-value = 0.739
## Believe
## Gender Yes No
## Female 0.3987168 0.3437214
## Male 0.1347388 0.1228231
As you can see we can calculate our chi-square statistic really quickly for two-way tables or larger. Now we can standardize this contingency measure to see if the relationship is significant.
##
## Attaching package: 'DescTools'
## The following objects are masked from 'package:psych':
##
## AUC, ICC, SD
## [1] 0.01218871
Let’s consider the titanic dataset which contains a complete list of passengers and crew members on the RMS Titanic. It includes a variable indicating whether a person did survive the sinking of the RMS Titanic on April 15, 1912. A data frame contains 2456 observations on 14 variables.
The website http://www.encyclopedia-titanica.org/ offers detailed information about passengers and crew members on the RMS Titanic. According to the website 1317 passengers and 890 crew member were aboard.
8 musicians and 9 employees of the shipyard company are listed as passengers, but travelled with a free ticket, which is why they have NA values in fare. In addition to that, fare is truely missing for a few regular passengers.