# We will use the following packages. # If needed, install them : pak::pkg_install(). stopifnot(require("corrr"),require("magrittr"),require("lobstr"),require("ggforce"),require("gt"),require("glue"),require("skimr"),require("patchwork"), require("tidyverse"),require("ggfortify")# require("autoplotly"))
It is enough to call summary() on each column of swiss. This can be done in a functional programming style using package purrr. The collections of summaries can be rearranged so as to build a dataframe that is fit for reporting.
Code
tt <-map_dfr(swiss, summary, .id ="var")
Code
tt |> gt::gt() |> gt::fmt_number(decimals=1)
var
Min.
1st Qu.
Median
Mean
3rd Qu.
Max.
Fertility
35.00
64.700
70.40
70.14255
78.450
92.5
Agriculture
1.20
35.900
54.10
50.65957
67.650
89.7
Examination
3.00
12.000
16.00
16.48936
22.000
37.0
Education
1.00
6.000
8.00
10.97872
12.000
53.0
Catholic
2.15
5.195
15.14
41.14383
93.125
100.0
Infant.Mortality
10.80
18.150
20.00
19.94255
21.700
26.6
Function skim from skimr delivers all univariate summaries in suitable form.
We have to pick some graphical summary of the data. Boxplots and violine plots could be used if we look for concision.
We use histograms to get more details about each column.
Not that covariates have different meanings: Agriculture, Catholic, Examination, and Education are percentages with values between \(0\) and \(100\).
We have no details about the standardized fertility index Fertility
Infant.Mortality is also a rate:
Infant mortality is the death of an infant before his or her first birthday. The infant mortality rate is the number of infant deaths for every 1,000 live births. In addition to giving us key information about maternal and infant health, the infant mortality rate is an important marker of the overall health of a society.
We reuse the function we have already developped during previous sessions.
Code
make_biotifoul(swiss, .f = is.numeric)
Histograms reveal that our covariates have very different distributions.
Religious affiliation (Catholic) tells us that there two types of districts, which is reminiscent of the old principle Cujus regio, ejus religio , see Old Swiss Confederacy.
Agriculture shows that in most districts, agriculture was still a very important activity.
Education reveals that in all but a few districts, most children did not receive secondary education. Examination shows that some districts lag behind the bulk of districts. Even less exhibit a superior performance.
The two demographic variables Fertility and Infant.Mortality look roughly unimodal with a few extreme districts.
Investigate pairwise correlations
Question
Compute, display and comment the sample correlation matrix
Display jointplots for each pair of variables
solution
Package corrr, functions correlate and rplot provide a convenient tool.
Note that corrr::rplot() creates a graphical object of class ggplot. We can endow it with more layers.
The high positive linear correlation between Education and Examination is moderately surprising. The negative correlation between the proportion of people involved in Agriculture and Education and Examinationis also not too surprising. Secondary schooling required pupils from rural areas to move to cities.
A more intriguing observation concerns the pairs Catholic and Examination (negative correlation) and Catholic and Education (little correlation).
The response variable Fertility looks negatively correlated with Examination an Education. These correlations are worth being further explored. In Demography, the decline of Fertility is often associated with the the rise of women education. Note that Examination is about males, and that Education does not give details about the way women complete primary education.
Singular Value Decomposition (SVD)
Question
Project the swiss dataset on the covariates (all columns but Fertility)
Center the projected data using matrix manipulation
Center the projected data using dplyr verbs
Compare the results with the output of scale() with various optional arguments
Call the centered matrix Y
solution
Hand-made centering of the dataframe emphasises the fact that centering is a linear operation. As a matter of fact, it consists in projecting the data frame on the linear space orthogonal to the constant vector.
Code
X <-select(swiss, -Fertility) |>as.matrix()n <-nrow(X)ones <-matrix(1, nrow = n, ncol=1) Y <- X - (1/n)* (ones %*%t(ones) %*% X)
We can also perform centering using dplyr verbs. This can be viewed as computing a window function over a trivial partition.
Note that we used the exposing pipe %$% from magrittr to unpack svd_Y which is a list with class svd and members named u, d and v.
We could have used with(,) from base R.
Question
Relate the SVD of \(Y\) and the eigen decomposition of \(Y^\top \times Y\)
solution
The matrix \(1/n Y^\top \times Y\) is the covariance matrix of the covariates.
The spectral decomposition of the symmetric Semi Definite Positive (SDP) matrix \(1/n Y^\top \times Y\) is related with the SVD factorization of \(Y\).
The spectral/eigen decomposition of \(Y^\top \times Y\) can be obtained using eigen().
The eigenspaces of \(Y^\top \times Y\) are the right eigenspaces of \(Y\).
Code
(t(eigen(t(Y) %*% Y )$vectors) %*% svd_Y$v ) %>%round(digits=2)
Here, the eigenvectors of \(Y^\top \times Y\) coincide with the right singular vectors of \(Y\) corresponding to non-zero singular values. Up to sign changes, it is always true when the non-zero singular values are pairwise distinct.
Perform PCA on covariates
Question
Pairwise analysis did not provide us with a clear and simple picture of the French-speaking districts.
PCA (Principal Component Analysis) aims at exploring the variations of multivariate datasets around their mean (center of inertia). In the sequel, we will perform PCA on the matrix of centered covariates, with and without standardizing the centered columns.
Base R offers prcomp(). Call prcomp() on the centered covariates
Note that R also offers princomp
We first call prcomp() with the default arguments for centering and scaling, that is, we center columns and do not attempt to standardize columns. Name the output pco.
pco is a list with 5 members. It as a class attribute prcomp. It is an object of class prcomp (function prcomp() acts as a constructor for class pco just as lm() acts as a constructor for class lm). Class pco is an S3 class
Code
rlang::is_list(pco)
[1] TRUE
Code
attributes(pco)
$names
[1] "sdev" "rotation" "center" "scale" "x"
$class
[1] "prcomp"
Code
sloop::s3_class(pco)
[1] "prcomp"
Question
Check that prcomp() is indeed a wrapper for svd().
solution
We first check that the matrix can be recovered from the product of the components of the prcomp object.
Make a scatterplot from the first two columns of the \(x\) component of the prcomp object.
solution
Objects of class prcomp can be handled by generic functions like plot() or better autoplot(). Namely, method prcomp for generic S3 function autoplot() from ggplot2 delivers one of classical SVD plots.
Code
res <-autoplot(pco) +coord_fixed() +theme_minimal()ts <-theme_set(theme_minimal())res
autoplot(pco) is a scatterplot for the dataframe defined by matrix \(U \times D\) projected on its first two principal components (first two columns).
As autoplot(pco) is an instance of class ggplot, it can be annotated, decorated as any other ggplot object.
Code
( res +aes(color=Catholic) +theme_minimal()) +( res +aes(color=Education) +theme_minimal()) + patchwork::plot_annotation(subtitle ="Scatterplot on the first two principal components (no column scaling)",title="Share of catholics can almost be determined from the sign of the first PC",caption ="Swiss Fertility data from R datasets" )
Question
Define a graphical pipeline for the screeplot.
Hint: use function tidy() from broom, to get the data in the right form from an instance of prcomp.
solution
The screeplot is a bar plot where each bar corresponds to a singular value. The bar height is proportional to the square of the corresponding singular value.
Mind the braces on the right side of the first pipe
3
1- cumulative tell the reader about the relative Frobenious error achieved by keeping the first components of the SVD expansion.
Code
pco %>%p_screeplot() +ylab('Relative squared Frobenius error/Relative squared error') +labs(title="Screeplot for swiss fertility data",subtitle="Keeping the first two components is enough to achieve relative Froebenius relative error 3.3%") +theme_minimal()
The screeplot is a visualization of the Eckart-Young-Mirsky Theorem. It tells us about the relative errors incurent when approximating the data matrix (with centered columns) by the low rank approximations defined by the truncated SVDs.
Question
Define a function that replicates autoplot.prcomp()
Project the dataset on the first two principal components (perform dimension reduction) and build a scatterplot. Colour the points according to the value of original covariates.
Hint: use generic function augment from broom.
solution
Code
p <- pco %>% broom::augment(swiss) %>%ggplot() +aes(x=.fittedPC1, y=.fittedPC2, label=.rownames) +geom_point() +coord_fixed() + ggrepel::geom_text_repel() +theme_minimal()(p +aes(color=Infant.Mortality)) +(p +aes(color=Education)) +(p +aes(color=Examination)) +(p +aes(color=Catholic)) +(p +aes(color=Agriculture)) +(p +aes(color=Fertility)) +plot_layout(ncol =2) +plot_annotation(title="Swiss data on first two PCs" , subtitle ="centered, unscaled")
Question
Apply broom::tidy() with optional argument matrix="v" or matrix="loadings" to the prcomp object.
Comment.
solution
We can extract factor \(V\) from the SVD factorization using generic function tidy from package broom
The length of each arrow is the length of the projection of the corresponding column of the data matrix over the plane generated by the first two rescaled left singular vectors (rescaling by the reciprocal of the singular values).
The first two principal componants (left singular vectors) are highly correlated with columns Agriculture and Catholic.
Question
Compute PCA after standardizing the columns, draw the correlation circle.
Warning: The `x` argument of `as_tibble.matrix()` must have unique column names if
`.name_repair` is omitted as of tibble 2.0.0.
ℹ Using compatibility `.name_repair`.
Biplot
Question
The last svd plot (biplot) consists of overlaying the scatter plot of component x of the prcomp object and the correlation circle.
So the biplot is a graphical object built on two dataframes derived on components x and rotation of the prcomp objects.
Warning: ggrepel: 21 unlabeled data points (too many overlaps). Consider
increasing max.overlaps
Question
autoplot.prcomp() has optional arguments. If set to True, logical argument loadings overlays the scatterplot defined by the principal components with the correlation circle.