Package {corx}


Type: Package
Title: Create and Format Correlation Matrices
Version: 1.0.8
Date: 2026-11-25
Description: Create correlation (or partial correlation) matrices. Correlation matrices are formatted with significance stars based on user preferences. Matrices of coefficients, p-values, and number of pairwise observations are returned. Send resultant formatted matrices to the clipboard to be pasted into excel and other programs. A plot method allows users to visualize correlation matrices created with 'corx'.
License: MIT + file LICENSE
Encoding: UTF-8
URL: https://github.com/conig/corx
Depends: R (≥ 3.6)
Imports: crayon, ggcorrplot, glue, clipr, tidyselect (≥ 1.2.0), rlang, moments, ggpubr, ggplot2, stats, methods, ppcor, labelled
Suggests: papaja, psych, testthat
Config/roxygen2/version: 8.1.1
NeedsCompilation: no
Packaged: 2026-11-25 03:10:00 UTC; R-package-build
Author: James Conigrave ORCID iD [aut, cre]
Maintainer: James Conigrave <james.conigrave@gmail.com>
Repository: CRAN
Date/Publication: 2026-11-25 04:00:30 UTC

adjust_p

Description

adjust_p

Usage

adjust_pmat(
  pmat,
  p_adjust,
  pairs = shared_pair_cells(rownames(pmat), colnames(pmat))
)

Arguments

pmat

named matrix of p-values to adjust

p_adjust

character describing adjustment to make. See stats::p.adjust

pairs

positions of self-comparisons and reversed pairs in pmat


apa matrix

Description

Creates an apa matrix

Usage

apa_matrix(r_matrix, p_matrix, stars, round, remove_lead, triangle, self)

Arguments

r_matrix

correlation coefficient matrix

p_matrix

p-value matrix

stars

a vector of pvalue stars

round

How many digits to round to?

remove_lead

a logical. Should leading zeros be removed?

triangle

can select lower upper or NULL

self

logical matrix identifying comparisons of a variable with itself


Format a correlation table with papaja

Description

Method for papaja::apa_table() that uses the formatted table from a corx() object.

Usage

apa_table.corx(x, ...)

Arguments

x

A corx() object.

...

Additional arguments passed to papaja::apa_table(). Specify caption or note here to override the values stored in the object. The method supplies the table itself.

Value

The result of papaja::apa_table(), in the format selected by that function.

See Also

to_table().


check_classes

Description

check all classes are as expected

Usage

check_classes(data, ok_classes, stop_message, stop = TRUE)

Arguments

data

the data object

ok_classes

a vector of allowed classes

stop_message

a character string provided to users if error triggers.

stop

should the variable stop, or create a warning?


Extract results from a correlation table

Description

Use coef() to extract unrounded coefficients, or use summary() and as.data.frame() to extract the formatted table.

Usage

## S3 method for class 'corx'
coef(object, ...)

## S3 method for class 'corx'
summary(object, ..., digits, quantile.type)

## S3 method for class 'corx'
as.data.frame(x, ...)

Arguments

object, x

A corx() object.

...

Unused; included for compatibility with the generics.

digits, quantile.type

Unused arguments to the summary() method. To change rounding, set round when calling corx().

Value

coef() returns the numeric coefficient matrix. summary() and as.data.frame() return the formatted table as a data frame, with the table's original column names.

Examples

fit <- corx(mtcars[, 1:3])
coef(fit)
summary(fit)
as.data.frame(fit)

cormat_list

Description

cormat_list

Usage

cormat_list(data, x, y, z, method, p_adjust)

Arguments

data

data.frame

x

named column positions for the row variables

y

named column positions for the column variables

z

column positions of the control variables, or NULL

method

string, passed to cor.test

p_adjust

string, passed to p.adjust


Compute and format a correlation matrix

Description

Compute ordinary or partial correlations and format them for an APA-style table. Unrounded coefficients, p-values, and observation counts are also available separately.

Usage

corx(
  data,
  x = NULL,
  y = NULL,
  z = NULL,
  method = c("pearson", "spearman", "kendall"),
  stars = c(0.05, 0.01, 0.001),
  p_adjust = c("none", "holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr"),
  round = 2,
  remove_lead = TRUE,
  triangle = NULL,
  caption = NULL,
  note = NULL,
  describe = FALSE,
  grey_nonsig = TRUE,
  call_only = FALSE
)

Arguments

data

A data frame or matrix with at least three rows. Selected columns must be numeric or integer. Numeric columns with value labels are accepted; character and factor columns are not.

x

Column selection for the rows of the result. The default, NULL, selects all columns. Use bare names, quoted names, or tidyselect helpers such as where(is.numeric). For a character vector stored in cols, use tidyselect::all_of(cols). An explicit selection must match a column. Use c(Label = column) to label a variable without renaming the input.

y

Column selection for the columns of the result, using the same syntax as x. The default, NULL, uses the selection in x. An explicit selection must match a column. Labels on the two axes may differ.

z

Column selection for control variables, using the same syntax as x. The default, NULL, computes ordinary correlations. Selected controls are removed from both axes of the result.

method

Correlation method: "pearson" (the default), "spearman", or "kendall".

stars

Numeric p-value thresholds, listed from largest to smallest. Each threshold a p-value falls strictly below adds one star. Use NULL or numeric(0) to omit stars.

p_adjust

Multiple-testing adjustment passed to stats::p.adjust(): "none" (the default), "holm", "hochberg", "hommel", "bonferroni", "BH", "BY", or "fdr".

round

Number of decimal places in the formatted table. The default is 2. This does not round the stored coefficients or p-values.

remove_lead

Logical. If TRUE (the default), omit leading zeros from formatted coefficients (for example, .42 instead of 0.42).

triangle

Which part of a square matrix with the same variables in the same order on both axes to show in the formatted table: "lower", "upper", or NULL (the default) for the full table. The stored numeric matrices are not cropped.

caption

Optional character string printed above the table and used as the default plot title.

note

Optional character string printed below the table. If NULL, a note is generated from the significance thresholds in stars.

describe

Descriptive statistics to append for each row variable. Use FALSE (the default) for none, TRUE for the mean and standard deviation, or a named list of functions that each accept a column and return one value. You can also select the built-in summaries mean, sd, var, median, iqr, skewness, kurtosis, and n (the number of nonmissing values), for example c(M = mean, n). The built-in summaries remove missing values from each variable independently; custom functions handle missing values themselves.

grey_nonsig

Logical. If TRUE (the default), print coefficients without significance stars in grey when stars are enabled and describe = FALSE. This affects console output only.

call_only

Logical. If TRUE, return the matched call and its environments for debugging, without computing correlations. The default is FALSE.

Details

Ordinary Pearson correlations use the two-sided t test with n - 2 degrees of freedom. Ordinary rank correlations use the asymptotic p-values from stats::cor.test(). Partial correlations use ppcor::pcor.test().

Missing data. Each pair uses only the rows observed for both variables and all controls. The n matrix records this count, even when it is zero. Ordinary correlations based on fewer than two observations have missing coefficients and p-values. With exactly two observations, ordinary Pearson and Spearman correlations have a coefficient but no p-value. Partial tests require at least three observations beyond the number of controls (two for Kendall); otherwise both the coefficient and p-value are missing.

Multiple comparisons. The adjustment is applied to distinct unordered variable pairs in the matrix. Self-correlations are excluded and their p-values are left unchanged. If a pair appears in both orientations, both cells receive the same adjusted p-value. The display selected by triangle does not change the set of comparisons.

Value

A list of class corx with the following components:

With call_only = TRUE, the result is an unclassed list containing the matched call, the function's evaluation environment (env), and the calling environment (parent_env).

See Also

corx-methods, print.corx(), plot.corx(), plot_mds(), to_table(), to_clipboard().

Examples

fit <- corx(mtcars, x = c(mpg, cyl, disp), y = c(drat, qsec),
            z = wt, caption = "Controlling for weight",
            describe = list(M = function(x) mean(x, na.rm = TRUE)))
fit
coef(fit)
fit$p

corx(iris[, 1:4], describe = c(median, IQR = iqr, n), triangle = "lower")

digits

Description

Consistent rounding for strings

Usage

digits(x, n = 2)

Arguments

x

number to round

n

number of digits


Plot a correlation matrix

Description

Plot the coefficients and p-values stored in a corx() object using ggcorrplot::ggcorrplot().

Usage

## S3 method for class 'corx'
plot(x, ...)

Arguments

x

A corx() object.

...

Named arguments passed to ggcorrplot::ggcorrplot(). Use type or title to override the defaults. The coefficient and p-value matrices are supplied from x; do not pass corr or p.mat.

Details

The plot uses the triangle setting from the original call, or "full" if none was supplied. The caption in the original call supplies the default title.

Value

A ggplot object.

See Also

plot_mds().

Examples

fit <- corx(mtcars[, 1:4])
plot(fit, type = "lower", title = "Motor Trend car data")

Plot correlations using multidimensional scaling

Description

Show variables as points in a two-dimensional map, with similar variables placed near one another. Optionally group the points with k-means clustering.

Usage

plot_mds(corx, k = NULL, abs = TRUE, ...)

Arguments

corx

A corx() object with at least three variables, matching row and column names in the same order, and no missing coefficients.

k

Number of clusters, as a positive integer no larger than the number of variables. The default, NULL, skips clustering. Use "auto" to count the principal components that each explain more than 5% of the variance in a PCA of the correlation matrix used for scaling.

abs

Logical. If TRUE (the default), use absolute correlations so that strongly negative and strongly positive correlations both imply similarity. If FALSE, retain the signs.

...

Additional arguments passed to ggpubr::ggscatter(). Do not supply arguments already set by this function, such as x, y, or label.

Details

This function requires the psych package. Correlations are converted to distances with psych::cor2dist():

d = \sqrt{2(1-r)}

Here, r is the signed or absolute correlation, as specified by abs. Classical multidimensional scaling with stats::cmdscale() embeds the distances in two dimensions. The function warns if the squared correlation between the original distances and the distances in the map is below 0.70. When clustering is requested, stats::kmeans() uses the two-dimensional coordinates.

Value

A ggplot object.

References

Carlson, D. L. (2017). Quantitative Methods in Archaeology Using R. Cambridge University Press.

See Also

plot.corx() for a plot of the correlation matrix itself.

Examples

fit <- corx(mtcars[, 1:4])
if (requireNamespace("psych", quietly = TRUE)) plot_mds(fit)

Print a formatted correlation table

Description

Print the original call, the formatted table, and its caption and note.

Usage

## S3 method for class 'corx'
print(x, ...)

Arguments

x

A corx() object.

...

Unused; included for compatibility with the print() generic.

Value

NULL, invisibly. The table is written to the console.

See Also

corx-methods, to_table().


star_matrix

Description

Replaces p-values with stars

Usage

star_matrix(m, stars)

Arguments

m

matrix of p-values

stars

a vector of p-value thresholds to replace with stars


Copy a formatted correlation table to the clipboard

Description

Copy a table for pasting into a spreadsheet or another application. This function requires an interactive R session and an available system clipboard. In scripts, use to_table() to get the formatted table instead.

Usage

to_clipboard(x, ...)

Arguments

x

A corx() object, matrix, or data frame. For a corx object, only the formatted table (x$apa) is copied, without the caption or note.

...

Additional arguments passed to clipr::write_clip().

Value

Invisibly returns the value from clipr::write_clip() (the original content by default, or the formatted text if return_new = TRUE).

See Also

to_table() to extract a table without using the clipboard.


Extract a formatted correlation table

Description

Extract the formatted table from a corx() result, optionally adding p-values on a separate row beneath each row of coefficients.

Usage

to_table(corx, include_p = FALSE)

Arguments

corx

A corx() object.

include_p

Logical. If FALSE (the default), return the formatted table as stored in the object. If TRUE, add rows for the stored p-values, which are adjusted if requested in corx().

Value

If include_p = FALSE, the formatted character matrix. Otherwise, a data frame with alternating coefficient and p-value rows. Descriptive statistics have no corresponding p-value; those cells are missing.

See Also

corx-methods, to_clipboard().

Examples

fit <- corx(mtcars[, 1:4])
to_table(fit)
to_table(fit, include_p = TRUE)

mirror server hosted at Truenetwork, Russian Federation.