Written and maintained by CASRAI Editorial Board
Published
On this page
To build a correlation matrix in R, pass a numeric matrix or data frame to cor() from the base stats package: cor(df) returns a square matrix with one row and one column per variable. That matrix holds coefficients only. If you also need p-values or the number of observations behind each cell, use rcorr() from the Hmisc package, and if you want to see the matrix as a plot, pass it to corrplot() from the corrplot package. This guide walks through all three on built-in datasets, with the missing-data options laid out side by side.
What a correlation matrix in R is used for in research
A matrix of correlations in R is the table of pairwise correlation coefficients among a set of variables. Researchers use it to screen a dataset before modelling, to report the zero-order associations among scale scores or measured outcomes, and to spot variable pairs so strongly related that they may cause trouble in a regression. Interpreting the numbers is a separate task, covered in how to read a correlation matrix; the covariance counterpart is explained in covariance matrix. This page is about producing the matrix in R and choosing the right function for the output you need.
The data table below the article compares four functions that people often confuse: what each takes, whether it returns a matrix, and how it treats missing values. The short version is that cor() and rcorr() return matrices, while cor.test() works on exactly two variables and does not.
Install or access (official source only)
cor(), cov(), cov2cor() and cor.test() are part of the stats package that is loaded in every R session, so nothing needs installing. The datasets used below (mtcars, swiss, longley, USJudgeRatings) ship with base R and are used in the official documentation examples.
Hmisc and corrplot are CRAN packages. R itself and CRAN package pages are published at cran.r-project.org. From an R session:
install.packages(c("Hmisc", "corrplot"))library(Hmisc)library(corrplot)
Step-by-step: build a correlation matrix in R
1. Compute the matrix with cor()
The documented usage is cor(x, y = NULL, use = "everything", method = c("pearson", "kendall", "spearman")). When x is a matrix or data frame and y is left as NULL, y is treated as equal to x, and the correlations between all pairs of columns of x are returned. Every column must be numeric.
M <- cor(mtcars)round(M, 2)
Wrapping the result in round() only shortens the display; it does not change the stored matrix.
2. Choose the correlation method
Pearson is the default. For a rank-based matrix, set method to "spearman" or "kendall"; the documentation notes that Kendall and Spearman are rank-based and that Kendall with ties computes tau-b. The method name may be abbreviated.
cor(mtcars, method = "spearman")
3. Decide how to handle missing values
This is the argument that most often changes a result. The default, use = "everything", propagates missing values: a cell is NA whenever any observation contributing to it is NA. Section “Missing data” below sets out all five options.
swM <- as.matrix(swiss)swM[1, 2] <- swM[7, 3] <- swM[25, 5] <- NA # inject three missing values, as in the R documentation examplecor(swM) # NA appears in every cell touching a damaged columncor(swM, use = "complete.obs") # casewise deletioncor(swM, use = "pairwise.complete.obs") # pairwise deletion
4. Get p-values and pair counts with rcorr()
Hmisc’s rcorr(x, y, type = c("pearson", "spearman")) returns a Pearson or Spearman correlation matrix with pairwise deletion of missing data. If you supply only x, it must be a numeric matrix with at least 5 rows and 2 columns, so convert a data frame first:
res <- rcorr(as.matrix(mtcars)) # Pearson by defaultres$r # correlation matrixres$n # number of pairs used for each cellres$P # asymptotic P-values
The value of rcorr() is a list. r holds the correlations (NA where fewer than two non-missing pairs exist), n the pair counts (the diagonal is the count of non-missing values for that variable), and P the asymptotic P-values from a t or F approximation. For Spearman, use rcorr(as.matrix(mtcars), type = "spearman"). Kendall is not an option in rcorr(); use cor(method = "kendall") for coefficients.
5. Plot the matrix with corrplot()
The corrplot package draws a matrix produced by cor(). Its vignette (corrplot 0.95) shows these calls:
library(corrplot)M <- cor(mtcars)corrplot(M, method = "number") # print the coefficientscorrplot(M) # default: circlescorrplot(M, method = "color", order = "alphabet")
Seven display methods are documented: circle, square, ellipse, number, shade, color and pie. The type argument takes full, upper or lower, and order can reorder variables, including by coefficient pattern. For a general heatmap approach beyond correlations see heatmap in R.
6. Test every pair with cor.mtest()
corrplot also provides cor.mtest(mat, ...), where mat has samples in rows and features in columns. Extra arguments are passed to cor.test(), for example conf.level = 0.95. It returns a list with p, lowCI and uppCI, each a square matrix of the same layout as the correlation matrix.
tst <- cor.mtest(mtcars, conf.level = 0.95)tst$p # matrix of p-valuestst$lowCI # lower confidence limitstst$uppCI # upper confidence limits
Missing data: what each use= option does
The use argument of cor() accepts five values. The table is taken from the base R help page for cor.
| use = | Behaviour | Consequence for the matrix |
|---|---|---|
"everything" (default) |
NAs propagate | Result is NA wherever a contributing observation is NA |
"all.obs" |
Missing observations are not allowed | An error is raised if any are present |
"complete.obs" |
Casewise deletion | Only rows complete on all variables are used; error if there are no complete cases |
"na.or.complete" |
Same as complete.obs | Returns NA instead of an error if there are no complete cases |
"pairwise.complete.obs" |
Pairwise deletion | Each cell uses all complete pairs for that variable pair; the documentation warns the result may not be positive semi-definite |
The documentation’s examples use the abbreviations "complete" and "pairwise", so partial matching is accepted. With pairwise deletion, each cell can rest on a different number of observations; rcorr() reports those counts in $n, which is the practical reason to prefer it when you must report how many cases each coefficient used. For a worked comparison of the same choice in other software, see correlation matrices in Stata: correlate vs pwcorr.
Output and how to read it
cor() returns a symmetric matrix whose diagonal is 1 and whose off-diagonal cells are the coefficients between the named row and column variables. Row and column names come from the column names of the input. rcorr() returns three matrices of the same shape: coefficients (r), pair counts (n) and P-values (P). Read a cell of r together with the same cell of n and P; a large coefficient resting on few pairs deserves less confidence than the same coefficient on many.
When rows with missing values are involved, check the n matrix before reporting anything. Interpretation guidance, including strength labels and the difference between correlation and causation, is in how to read a correlation matrix, and the single-pair function cor() with its test counterpart is covered in cor in R.
Troubleshooting
- “‘x’ must be numeric”.
cor()needs numeric columns. Select them first, for exampledf[sapply(df, is.numeric)]. - NA in many cells. You are using the default
use = "everything". Choosecomplete.obsorpairwise.complete.obsdeliberately and report which. - Error from
use = "all.obs"or fromcomplete.obs. The first errors on any missing value; the second errors when no row is complete.na.or.completereturns NA instead. rcorr()complains about the input. It needs a matrix, not a data frame, with at least 5 rows and 2 columns: wrap the data inas.matrix().- NA for a single-observation case. The documentation states that
cor()returns NA when there is only one observation. - A p-value matrix from
cor.test().cor.test()compares exactly two variables and will not return a matrix; usercorr()$Porcor.mtest()for all pairs.
Free alternatives
| Task | Route | Where it is documented |
|---|---|---|
| Correlation matrix, no package | cor() in base R |
R documentation, stats package |
| Matrix with P-values and pair counts | rcorr() in Hmisc |
CRAN, Hmisc manual |
| Matrix plot | corrplot() in corrplot |
CRAN, corrplot vignette |
| Matrix of tests and confidence intervals | cor.mtest() in corrplot |
corrplot manual |
| Same task in Python | pandas DataFrame.corr() |
see pandas corr |
R and all packages named here are free to download from CRAN. For a package that adds correlation tools alongside psychometric functions, see the psych package in R.
FAQ
How do I make a correlation matrix in R?
Call cor(df) on a data frame or matrix of numeric columns. It returns a square matrix of Pearson coefficients by default; add method = "spearman" for a rank-based version.
How do I get p-values for a correlation matrix in R?
Use rcorr(as.matrix(df))$P from Hmisc for asymptotic P-values, or cor.mtest(df)$p from corrplot, which applies cor.test() to each pair and also returns confidence limits.
How do I handle missing values in a correlation matrix in R?
Set the use argument. "complete.obs" deletes whole rows with any NA; "pairwise.complete.obs" uses every complete pair for each cell. Both can be defended, but report which you used, because pairwise results may not be positive semi-definite.
How do I make a Spearman correlation matrix in R?
Use cor(df, method = "spearman") or rcorr(as.matrix(df), type = "spearman") if you also want P-values and counts.
How do I plot a correlation matrix in R?
Pass the matrix to corrplot(), for example corrplot(cor(mtcars), method = "color").
Sources
- R Core Team, Correlation, Variance and Covariance (Matrices): cor, read 2026-11-12.
- R Core Team, Test for Association/Correlation Between Paired Samples: cor.test, read 2026-11-12.
- Hmisc package, reference manual on CRAN and the rcorr help page, read 2026-11-12.
- corrplot package, An Introduction to corrplot and cor.mtest help page, read 2026-11-12.
Data: Functions for a correlation matrix in R: inputs, outputs and missing-data handling
Compares four R functions (cor, rcorr, cor.test, cor.mtest) on input type, whether they return a matrix, P-value and confidence-interval output, missing-data handling and methods, compiled from the official R, Hmisc and corrplot documentation.
| Function | Package | Input | Returns a matrix | P-values | Confidence interval | Missing-data handling | Methods |
|---|---|---|---|---|---|---|---|
| cor() | stats (base R) | numeric vector, matrix or data frame; optional y | Yes: correlations between columns of x (and y) | No | Not provided | use= (everything, all.obs, complete.obs, na.or.complete, pairwise.complete.obs) | pearson, kendall, spearman |
| rcorr() | Hmisc (CRAN) | numeric matrix, at least 5 rows and 2 columns | Yes: r, n, P | Yes (P) | Not provided | Pairwise deletion | pearson, spearman |
| cor.test() | stats (base R) | two variables (x, y) or formula ~ u + v | No: one pair only | Yes | Yes (Pearson only, needs at least 4 complete pairs) | Not stated as a matrix option | pearson, kendall, spearman |
| cor.mtest() | corrplot (CRAN) | matrix with samples in rows and features in columns | Yes: p, lowCI, uppCI | Yes (p) | Yes (lowCI, uppCI) | Arguments passed on to cor.test() | As passed to cor.test() |
Sources
- R stats: cor (accessed 2026-11-12)
- R stats: cor.test (accessed 2026-11-12)
- Hmisc rcorr (accessed 2026-11-12)
- corrplot cor.mtest (accessed 2026-11-12)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







