ZetCode

R correlation

last modified November 19, 2026

Correlation measures how strongly two numeric variables move together. Covariance measures the same thing on the original scale, while correlation divides it by the two standard deviations and produces a number between minus one and one. R provides cov, cor, and cor.test, and the test reports a confidence interval and a p-value alongside the estimate. This article covers covariance, the Pearson, Spearman, and Kendall methods, missing values in a correlation matrix, and the difference between an association and a cause.

Covariance and correlation

Covariance is the average product of the deviations of two variables from their means. A positive value means that the variables tend to be above their means at the same time, and a negative value means that one tends to be above its mean when the other is below. Its size depends on the units, so it is hard to compare across problems.

covariance.R
hours <- c(2, 3, 5, 6, 8, 9, 11, 12)
scores <- c(55, 62, 68, 74, 79, 85, 88, 94)
cat("mean hours:", mean(hours), "\n")
cat("mean scores:", mean(scores), "\n")
cat("sd hours:", sd(hours), "\n")
cat("sd scores:", sd(scores), "\n")
cat("covariance:", cov(hours, scores), "\n")
cat("correlation:", cor(hours, scores), "\n")

Hours average 7 and scores average 75.625, with standard deviations of 3.63 and 13.43. The covariance is 48.29, measured in hours multiplied by points, a unit that has no practical meaning. The correlation is 0.992, which says that the two variables lie almost perfectly on an increasing line. Correlation removes the units by standardising both variables, so the result always falls between minus one and one regardless of what was measured.

$ Rscript covariance.R
mean hours: 7 
mean scores: 75.625 
sd hours: 3.625308 
sd scores: 13.42639 
covariance: 48.28571 
correlation: 0.9920067 

The Pearson test

cor.test tests the null hypothesis that the population correlation is zero. The default method is Pearson, which measures the strength of a linear relationship. The output includes the test statistic, the degrees of freedom, the p-value, a confidence interval, and the estimate.

pearson.R
hours <- c(2, 3, 5, 6, 8, 9, 11, 12)
scores <- c(55, 62, 68, 74, 79, 85, 88, 94)
print(cor.test(hours, scores))

The estimate is 0.992, and the confidence interval runs from 0.955 to 0.999. The p-value of 1.3e-06 is far below 0.05, so the hypothesis of no linear association is rejected. With only eight observations the interval is wide even though the estimate is close to one, which is the correct behaviour: a small sample supports a strong claim less precisely than a large one.

$ Rscript pearson.R

	Pearson's product-moment correlation

data:  hours and scores
t = 19.257, df = 6, p-value = 1.269e-06
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
 0.9547251 0.9986106
sample estimates:
      cor 
0.9920067 

Spearman's rank correlation

Spearman's method replaces the values with their ranks before computing the correlation. It measures whether the relationship is monotonic, meaning that one variable tends to increase whenever the other increases, without requiring that the increase be a straight line. The coefficient is called rho and is also bounded by minus one and one.

spearman.R
x <- c(1, 2, 3, 4, 5, 6)
y <- c(2, 4, 8, 16, 32, 64)
cat("pearson:", cor(x, y), "\n")
cat("spearman:", cor(x, y, method = "spearman"), "\n")
print(cor.test(x, y, method = "spearman"))

The values of y double at every step, so the relationship is exponential rather than linear. Pearson still reports 0.906 because the curve rises steadily over this short range, but Spearman reports exactly 1: the ranks are identical, so the relationship is perfectly monotonic. The p-value of 0.0028 comes from the exact distribution used for small samples. A perfect Spearman result does not imply a perfect straight line.

$ Rscript spearman.R
pearson: 0.9057639 
spearman: 1 

	Spearman's rank correlation rho

data:  x and y
S = 0, p-value = 0.002778
alternative hypothesis: true rho is not equal to 0
sample estimates:
rho 
  1 

Kendall's tau

Kendall's tau is built from pairs of observations. A pair is concordant when both variables move in the same direction from the first point to the second, and discordant when they move in opposite directions. The statistic compares the two counts and is often used with small samples or with many tied values.

kendall.R
x <- c(3, 1, 4, 2, 5, 6)
y <- c(2, 1, 5, 3, 4, 6)
print(cor(x, y, method = "kendall"))
print(cor.test(x, y, method = "kendall"))

Thirteen of the fifteen pairs are concordant, which gives a tau of 0.733. The p-value is 0.056, just above the five percent threshold, so this sample does not establish an association at that level. The estimate and the verdict point in different directions, which is why both should be reported. Kendall's tau is usually smaller than Spearman's rho for the same data because it counts pairs rather than squared rank differences.

$ Rscript kendall.R
[1] 0.7333333

	Kendall's rank correlation tau

data:  x and y
T = 13, p-value = 0.05556
alternative hypothesis: true tau is not equal to 0
sample estimates:
      tau 
0.7333333 

Missing values

A missing value in either variable makes the corresponding pair unusable. The default use = "everything" propagates the missing value and returns NA for every correlation that touches it. use = "complete.obs" keeps only the rows that are complete in all variables, while "pairwise.complete.obs" uses every pair that has two observed values.

cor-missing.R
df <- data.frame(
  x = c(1, 2, 3, 4, NA, 6),
  y = c(2, 3, 5, 4, 10, NA),
  z = c(5, 4, 2, 3, 1, 0)
)
print(cor(df))
print(cor(df, use = "complete.obs"))
print(cor(df, use = "pairwise.complete.obs"))

The default matrix has missing values everywhere except the diagonal. The complete-case matrix uses the first four rows, where all three variables are observed, and reports correlations of 0.8, -0.8, and -1. Pairwise deletion keeps the fifth row for the x-z pair and the sixth row for the x-y pair, which changes the x-z correlation to -0.932. Pairwise matrices can be inconsistent and even fail to be positive definite, so complete cases are the safer default for a formal analysis.

$ Rscript cor-missing.R
   x  y  z
x  1 NA NA
y NA  1 NA
z NA NA  1
     x    y    z
x  1.0  0.8 -0.8
y  0.8  1.0 -1.0
z -0.8 -1.0  1.0
           x          y          z
x  1.0000000  0.8000000 -0.9324324
y  0.8000000  1.0000000 -0.9138115
z -0.9324324 -0.9138115  1.0000000

A correlation matrix

cor and cov accept a data frame and return a square matrix with one row and column per variable. The diagonal of a correlation matrix is always one, and the matrix is symmetric. Rounding keeps a wide table readable, and the covariance matrix shows the same pattern on the original scale.

cor-matrix.R
df <- data.frame(
  hours = c(2, 3, 5, 6, 8, 9, 11, 12),
  scores = c(55, 62, 68, 74, 79, 85, 88, 94),
  motivation = c(6, 3, 8, 4, 7, 9, 5, 8)
)
print(round(cor(df), 3))
print(cov(df))

Hours and scores correlate at 0.992, while motivation correlates with each of them at about 0.43. The covariance between hours and scores is 48.29, the same value as in the first section, and the variances sit on the diagonal. A matrix makes it easy to spot the strong pair, but it does not say whether any of the coefficients is statistically distinguishable from zero.

$ Rscript cor-matrix.R
           hours scores motivation
hours      1.000  0.992      0.427
scores     0.992  1.000      0.425
motivation 0.427  0.425      1.000
               hours    scores motivation
hours      13.142857  48.28571   3.285714
scores     48.285714 180.26786  12.107143
motivation  3.285714  12.10714   4.500000

A complete example

The final script computes the correlation matrix and then tests every pair of variables one by one. The loop builds the pairs with combn, calls cor.test for each, and prints the estimate with its p-value. This is the compact form of a correlation table that would otherwise need one call per pair.

report.R
df <- data.frame(
  hours = c(2, 3, 5, 6, 8, 9, 11, 12),
  scores = c(55, 62, 68, 74, 79, 85, 88, 94),
  motivation = c(6, 3, 8, 4, 7, 9, 5, 8)
)
print(round(cor(df), 3))
pairs <- combn(names(df), 2, simplify = FALSE)
for (p in pairs) {
  test <- cor.test(df[[p[1]]], df[[p[2]]])
  cat(p[1], "-", p[2], ": r =", round(test$estimate, 3),
      " p =", format.pval(test$p.value, digits = 3), "\n")
}

Hours and scores are strongly associated, with r = 0.992 and a p-value of 1.27e-06. Motivation is only weakly related to both, and neither p-value reaches 0.05, so the sample does not establish those associations. The order of the pairs follows the column order of the data frame. A significant correlation is not evidence of causation: a third variable, such as prior knowledge, could drive both hours and scores, and only an experiment can rule that out.

$ Rscript report.R
           hours scores motivation
hours      1.000  0.992      0.427
scores     0.992  1.000      0.425
motivation 0.427  0.425      1.000
hours - scores : r = 0.992  p = 1.27e-06 
hours - motivation : r = 0.427  p = 0.291 
scores - motivation : r = 0.425  p = 0.294 

Next steps

The descriptive statistics article covers the standard deviations that standardise the covariance, and the probability distributions article explains the t distribution used by the Pearson test. The hypothesis testing article presents the p-value logic in more detail, and the linear regression article turns a correlation into a model that predicts one variable from another.

Source

R documentation: cor and cov

R documentation: cor.test

R documentation: round

In this article we have measured association with covariance and correlation, and tested it with the Pearson, Spearman, and Kendall methods. We saw how a monotonic but curved relationship leaves Pearson below one while Spearman reaches one, and how Kendall's tau counts concordant pairs. We handled missing values with complete cases and pairwise deletion, built a correlation matrix, and tested every pair in a small table. The series continues with R linear regression.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.