What is the correlation for the dataset \(\{ (0,0.1) , (1, 0.3), (2, 0.2) \}\)? Find the answer both mathematically and computationally.
Mathematically, there are five steps.
Step 1: Compute the means \[\begin{aligned}
\hat{m}_{X} &= \frac{0+1+2}{3} = 1 \\
\hat{m}_{Y} &= \frac{0.1+0.3+0.2}{3} = 0.2
\end{aligned}\]
Step 2: Compute the deviances \[
\begin{array}{c|rrrr}
\hat{x}_i & 0 & 1 & 2 \\
\hat{x}_i-\hat{m}_{X} & -1 & 0 & 1 \\
\hat{y}_i & 0.1 & 0.3 & 0.2 \\
\hat{y}_i-\hat{m}_{Y} & -0.1 & 0.1 & 0
\end{array}
\]
Step 3: Compute the Covariance \[\begin{aligned}
\hat{c}_{XY} &=
\sum (\hat{x}_i-\hat{m}_{X})(\hat{y}_i-\hat{m}_{Y})/n
= \left[ (-1)(-0.1) + 0(0.1) + 1(0) \right] \frac{1}{3}
= (0.1) \frac{1}{3}
= 1/30
\end{aligned}\]
Step 4: Compute Standard Deviations \[\begin{aligned}
\hat{v}_{X} &= \sum_{i=1}^n \left(\hat{x}_i-\hat{m}_{X}\right)^2 / n
= \left[(-1)^2+0^2+1^2 \right]/3
= 2/3 \\
\hat{s}_{X} &= \sqrt{2/3} \\
\hat{v}_{Y} &= \sum_{i=1}^n \left( \hat{y}_i-\hat{m}_{Y} \right)^2 / n
= \left[ (-0.1)^2+(0.1)^2+0^2 \right]/3
= \left[0.01+0.01\right]/3
= \frac{2}{100} \frac{1}{3} = 2/300 \\
\hat{s}_{Y} &= \sqrt{2/300}
\end{aligned}\]
Step 5: Compute the Correlation \[\begin{aligned}
\frac{\hat{c}_{XY}}{\hat{s}_X \hat{s}_Y}
&= \frac{1/30}{ \sqrt{2/3} \sqrt{2/300}}
= \frac{1/30}{ 2 /\sqrt{900}}
= \frac{1/30}{2/30} = 1/2
\end{aligned}\]
Note that this value suggests a positive relationship between the variables.
Computationally, we do the same steps
Code
# Create the Data
x0_hat <- c(0, 1, 2)
x0_hat
## [1] 0 1 2
y0_hat <- c(0.1, 0.3, 0.2)
y0_hat
## [1] 0.1 0.3 0.2
# Compute the Means
m_x_hat <- mean(x0_hat)
m_y_hat <- mean(y0_hat)
# Compute the Deviances
dev_X <- x0_hat - m_x_hat
dev_Y <- y0_hat - m_y_hat
# Compute the Covariance
cov_manual <- sum(dev_X * dev_Y) / length(x0_hat)
# Compute the Standard Deviations
v_x_hat <- sum(dev_X^2) / length(x0_hat)
s_x_hat <- sqrt(v_x_hat)
v_y_hat <- sum(dev_Y^2) / length(y0_hat)
s_y_hat <- sqrt(v_y_hat)
# Compute the Correlation
cor_manual <- cov_manual / (s_x_hat * s_y_hat)
cor_manual
## [1] 0.5
# Verify with the built-in function
cor(x0_hat, y0_hat)
## [1] 0.5