Descriptive Statistics

Bivariate Analysis

Evgenei Khodar, Marta Szulca

Introduction

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.

Data

This time we are going to use a typical credit scoring data with predefined “default” variables and personal demografic and income data. Please take a look closer at headers and descriptions of each variable.

Scatterplots

First let’s visualize our quantitative relationships using scatterplots.

You can also normalize the skewed distribution of incomes using log:

## The following objects are masked from bank (pos = 3):
## 
##     address, age, creddebt, debtinc, def, default, ed, educ, employ,
##     income, othdebt, preddef1, preddef2, preddef3

We can add an estimated linear regression line:

## The following objects are masked from bank (pos = 3):
## 
##     address, age, creddebt, debtinc, def, default, ed, educ, employ,
##     income, othdebt, preddef1, preddef2, preddef3
## The following objects are masked from bank (pos = 4):
## 
##     address, age, creddebt, debtinc, def, default, ed, educ, employ,
##     income, othdebt, preddef1, preddef2, preddef3
## `geom_smooth()` using formula = 'y ~ x'

Scatterplots by groups

We can finally see if there any differences between risk status:

## The following objects are masked from bank (pos = 3):
## 
##     address, age, creddebt, debtinc, def, default, ed, educ, employ,
##     income, logincome, othdebt, preddef1, preddef2, preddef3
## The following objects are masked from bank (pos = 4):
## 
##     address, age, creddebt, debtinc, def, default, ed, educ, employ,
##     income, othdebt, preddef1, preddef2, preddef3
## The following objects are masked from bank (pos = 5):
## 
##     address, age, creddebt, debtinc, def, default, ed, educ, employ,
##     income, othdebt, preddef1, preddef2, preddef3
## `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:

## `geom_smooth()` using formula = 'y ~ x'

# Marginal density plot of age (top panel)
ggMarginal(plot, groupFill=TRUE, groupColour=TRUE, margins = "x")
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using formula = 'y ~ x'

# Marginal density plot of y (right panel)
ggMarginal(plot, groupFill=TRUE, groupColour=TRUE, margins = "y")
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using formula = 'y ~ x'

We can also put those plots together:

## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using formula = 'y ~ x'

Scatterplots with density curves

We can also see more closely if there any differences between those two distributions adding their estimated density plots:

## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using formula = 'y ~ x'

Correlation coefficients - Pearson’s linear correlation

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.

Partial and semipartial correlation

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.

## [1] 0.3194263
## [1] 0.2203711

There is a weak correlation (Partial Correlation coefficient is 0.32) between log of income and age after controlling for years of employment.

How can we interpret the obtained partial correlation coefficient? What is the difference between that one and the semi-partial coefficient:

## [1] 9.905524

There is some correlation between the variables, but it isn’t particularly strong.

The partial correlation coefficient is 9.9 percentage points higher. That highlights the correlation of years of employment and age.

The semi-partial coefficient also measures the relationship between two variables controlling for the effect of additional variables, althrough not on both variables, but only one of them.

Rank correlation

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

As could be observed, Kendall method doesn’t show significant correlation.

Point-biserial correlation

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:

## 
##  Pearson's product-moment correlation
## 
## data:  as.numeric(bank$def) and bank$income
## t = -1.8797, df = 698, p-value = 0.06056
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  -0.144313546  0.003149751
## sample estimates:
##         cor 
## -0.07096966

Point-biserial coeffitient doesn’t show any relationship

Nonlinear correlation - eta coefficient

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.

## 
## Attaching package: 'effectsize'
## The following object is masked from 'package:psych':
## 
##     phi
## For one-way between subjects designs, partial eta squared is equivalent
##   to eta squared. Returning eta squared.
## # Effect Size for ANOVA
## 
## Parameter | Eta2 |       95% CI
## -------------------------------
## age       | 0.23 | [0.19, 1.00]
## 
## - One-sided CIs: upper bound fixed at [1.00].
## [1] -0.07096966

Eta correlation is weak, so no non-linear correlations observed

Correlation matrix

We can also prepare the correlation matrix for all quantitative variables stored in our data frame.

We can use ggcorr() function:

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.

Correlation matrix with scatterplots

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.call(grid.arrange, c(scatter_plot_list, ncol = 2))
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using formula = 'y ~ x'

Qualitative data

In case of two variables measured on nominal or ordinal&nominal scale - we are forced to organize so called “contingency” table with frequencies and calculate some kind of the correlation coefficient based on them. This is so called “contingency analysis”.

Let’s consider one example based on our data: verify, if there is any significant correlation between education level and credit risk.

cont_table <- table(bank$educ, bank$default)
cont_table
##    
##       0   1
##   1 293  79
##   2 139  59
##   3  57  30
##   4  24  14
##   5   4   1
cor(as.numeric(bank$educ), bank$default, method = "spearman")
## [1] 0.1239675

The correlation is very small, close to 0, so there’s no significant correlation.

Exercise 1. Contingency analysis.

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

## Call: cohen.kappa1(x = x, w = w, n.obs = n.obs, alpha = alpha, levels = levels, 
##     w.exp = w.exp)
## 
## Cohen Kappa and Weighted Kappa correlation coefficients and confidence boundaries 
##                   lower estimate upper
## unweighted kappa -0.043    0.011 0.065
## weighted kappa   -0.043    0.011 0.065
## 
##  Number of subjects = 1091
## 
##  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.

## [1] "Phi"
## [1] 0.01218871
## [1] "ContCoef"
## [1] 0.0121878
## [1] "CramerV"
## [1] 0.01218871
## [1] "TschuprowT"
## [1] 0.01218871

barplot(dane)

As could be observed, no significant relation between gender and the belief in the afterlife exists.

Exercise 2. Contingency analysis for the ‘Titanic’ data.

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.

# your answer here
library(naniar)
library(dlookr)
## Registered S3 methods overwritten by 'dlookr':
##   method          from  
##   plot.transform  scales
##   print.transform scales
## 
## Attaching package: 'dlookr'
## The following object is masked from 'package:psych':
## 
##     describe
## The following object is masked from 'package:tidyr':
## 
##     extract
## The following object is masked from 'package:base':
## 
##     transform
vis_miss(titanic, cluster = TRUE)

titanic%>%
  miss_case_table()
## # A tibble: 3 × 3
##   n_miss_in_case n_cases pct_cases
##            <int>   <int>     <dbl>
## 1              0    1296    52.8  
## 2              2    1152    46.9  
## 3              4       8     0.326
mean_age <- mean(titanic$Age, na.rm = TRUE)
titanic$Age[is.na(titanic$Age)] <- mean_age

titanic$Crew_or_Passenger_Flag <- ifelse(titanic$Crew.or.Passenger. == 'Passenger', 0, 1)
titanic$Gender_binary <- ifelse(titanic$Gender == 'Male', 0, 1)
titanic$Class_Department_Flag <- ifelse(titanic$Class...Department == '1st Class', 3, 
                                   ifelse(titanic$Class...Department == '2nd Class', 2, 
                                          ifelse(titanic$Class...Department == '3rd Class', 1, NA)))
titanic$Status_Flag <- ifelse(titanic$Status == 'Victim', 0, 1)
library(psych)

# Assuming your binary variables are binary_var1 and binary_var2
phi_coefficient_gender <- phi(table(titanic$Status_Flag, titanic$Gender_binary))
print(phi_coefficient_gender)
## Phi (adj.) |       95% CI
## -------------------------
## 0.37       | [0.33, 1.00]
## 
## - One-sided CIs: upper bound fixed at [1.00].
s_data <- data.frame(titanic$Status_Flag, titanic$Crew_or_Passenger_Flag)
s_data <- table(titanic$Status_Flag, titanic$Crew_or_Passenger_Flag)

s_data_matrix <- as.matrix(s_data)

print(chisq.test(s_data_matrix))
## 
##  Pearson's Chi-squared test with Yates' continuity correction
## 
## data:  s_data_matrix
## X-squared = 0.25137, df = 1, p-value = 0.6161
s_data <- data.frame(titanic$Status_Flag, titanic$Class_Department_Flag)
s_data <- table(titanic$Status_Flag, titanic$Class_Department_Flag)

s_data_matrix <- as.matrix(s_data)

print(chisq.test(s_data_matrix))
## 
##  Pearson's Chi-squared test
## 
## data:  s_data_matrix
## X-squared = 154.78, df = 2, p-value < 2.2e-16
point_biserial <- biserial.cor(titanic$Age, titanic$Status_Flag)
print(point_biserial)
## [1] -0.01473289

Considering results of all correlation tests, the most chances to survive had members of first class. Overall, ticket to better class significantly increased chances of survival for its holder.Also, women had slightly higher probability to evacuate. Between crew and passengers there is almost no difference, as well as while looking at the age of passengers.