library(tidyverse)

library(patchwork)

library(ggplot2)

library(CCA)

library(dplyr)

library(magrittr)

Data

Data <- data.frame( Sistolik = c(120, 109, 130, 121, 135, 140),

Diastolik = c(76, 80, 82, 78, 85, 87),

Tinggi = c(165, 180, 170, 185, 185, 187),

Berat = c(60, 80, 70, 85, 85, 87) )

Create data-frames

X <- Data %>% dplyr::select(Sistolik, Diastolik) %>% scale()

Y <- Data %>% dplyr::select(Tinggi, Berat) %>% scale()

Compute canonical correlations

cc <- cancor(X, Y)

str(cc)

print(cc) # Correlations between the canonical variates cc$cor

Canonical covariate Pairs

CC1_X <- as.matrix(X) %*% cc\(xcoef[, 1] CC1_Y <- as.matrix(Y) %*% cc\)ycoef[, 1]

CC2_X <- as.matrix(X) %*% cc\(xcoef[, 2] CC2_Y <- as.matrix(Y) %*% cc\)ycoef[, 2]

Create a dataframe with canonical covariates

cca_df <- Data %>% mutate(CC1_X = CC1_X, CC1_Y = CC1_Y, CC2_X = CC2_X, CC2_Y = CC2_Y)

Scatter plot between the first pair of canonical covariate

#| fig.width: 5.5 #| fig.height: 4 cca_df %>% ggplot(aes(x=CC1_X,y=CC1_Y))+ geom_point()

cca_df %>% ggplot(aes(x=CC2_X,y=CC2_Y))+ geom_point()

First Canonical Variate of X

p1 <- cca_df %>% ggplot(aes(x = as.factor(Sistolik), y = CC1_X)) + geom_boxplot(width = 0.5) + geom_jitter(width = 0.15, alpha = 0.6) + theme_minimal() + ggtitle(“First Canonical Variate of X”) + xlab(“Sistolik”) + ylab(“CC1_X”)

First Canonical Variate of Y

p2 <- cca_df %>% ggplot(aes(x = as.factor(Tinggi), y = CC1_Y)) + geom_boxplot(width = 0.5) + geom_jitter(width = 0.15, alpha = 0.6) + theme_minimal() + ggtitle(“First Canonical Variate of Y”) + xlab(“Tinggi”) + ylab(“CC1_Y”)

First Canonical Variate of X

p3 <- cca_df %>% ggplot(aes(x = as.factor(Sistolik), y = CC2_X)) + geom_boxplot(width = 0.5) + geom_jitter(width = 0.15, alpha = 0.6) + theme_minimal() + ggtitle(“First Canonical Variate of X”) + xlab(“Sistolik”) + ylab(“CC2_X”)

First Canonical Variate of Y

p4 <- cca_df %>% ggplot(aes(x = as.factor(Tinggi), y = CC2_Y)) + geom_boxplot(width = 0.5) + geom_jitter(width = 0.15, alpha = 0.6) + theme_minimal() + ggtitle(“First Canonical Variate of Y”) + xlab(“Tinggi”) + ylab(“CC2_Y”)

Combine plots

p1 + p2

p3 + p4