% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/latent_corr.R
\name{tetrachoric}
\alias{tetrachoric}
\alias{print.tetrachoric_corr}
\alias{plot.tetrachoric_corr}
\alias{summary.tetrachoric_corr}
\alias{print.summary.tetrachoric_corr}
\title{Pairwise Tetrachoric Correlation}
\usage{
tetrachoric(
  data,
  y = NULL,
  na_method = c("error", "pairwise"),
  ci = FALSE,
  p_value = FALSE,
  conf_level = 0.95,
  correct = 0.5,
  output = c("matrix", "sparse", "edge_list"),
  threshold = 0,
  diag = TRUE,
  ...
)

\method{print}{tetrachoric_corr}(
  x,
  digits = 4,
  n = NULL,
  topn = NULL,
  max_vars = NULL,
  width = NULL,
  show_ci = NULL,
  ...
)

\method{plot}{tetrachoric_corr}(
  x,
  title = "Tetrachoric correlation heatmap",
  low_color = "indianred1",
  high_color = "steelblue1",
  mid_color = "white",
  value_text_size = 4,
  show_value = TRUE,
  ...
)

\method{summary}{tetrachoric_corr}(
  object,
  n = NULL,
  topn = NULL,
  max_vars = NULL,
  width = NULL,
  ci_digits = 3,
  p_digits = 4,
  show_ci = NULL,
  ...
)

\method{print}{summary.tetrachoric_corr}(
  x,
  digits = NULL,
  n = NULL,
  topn = NULL,
  max_vars = NULL,
  width = NULL,
  show_ci = NULL,
  ...
)
}
\arguments{
\item{data}{A binary vector, matrix, or data frame. In matrix/data-frame mode,
only binary columns are retained.}

\item{y}{Optional second binary vector. When supplied, the function returns a
single tetrachoric correlation estimate.}

\item{na_method}{Character scalar controlling missing-data handling.
\code{"error"} rejects missing values. \code{"pairwise"} uses pairwise
complete cases.}

\item{ci}{Logical (default \code{FALSE}). If \code{TRUE}, attach
model-based large-sample Wald confidence intervals derived from the observed
information matrix of the latent-variable likelihood.}

\item{p_value}{Logical (default \code{FALSE}). If \code{TRUE}, attach
model-based large-sample Wald p-values and test statistics for each
estimated latent correlation.}

\item{conf_level}{Confidence level used when \code{ci = TRUE}. Default is
\code{0.95}.}

\item{correct}{Non-negative continuity correction added to zero-count cells.
Default is \code{0.5}.}

\item{output}{Output representation for the computed estimates.
\itemize{
\item \code{"matrix"} (default): full dense matrix; best when you need
matrix algebra, dense heatmaps, or full compatibility with existing code.
\item \code{"sparse"}: sparse matrix from \pkg{Matrix} containing only
retained entries; best when many values are dropped by thresholding.
\item \code{"edge_list"}: long-form data frame with columns
\code{row}, \code{col}, \code{value}; convenient for filtering, joins,
and network-style workflows.
}}

\item{threshold}{Non-negative absolute-value filter for non-matrix outputs:
keep entries with \code{abs(value) >= threshold}. Use
\code{threshold > 0} when you want only stronger associations (typically
with \code{output = "sparse"} or \code{"edge_list"}). Keep
\code{threshold = 0} to retain all values. Must be \code{0} when
\code{output = "matrix"}.}

\item{diag}{Logical; whether to include diagonal entries in
\code{"sparse"} and \code{"edge_list"} outputs.}

\item{...}{Additional arguments passed to \code{print()}.}

\item{x}{An object of class \code{summary.tetrachoric_corr}.}

\item{digits}{Integer; number of decimal places to print.}

\item{n}{Optional row threshold for compact preview output.}

\item{topn}{Optional number of leading/trailing rows to show when truncated.}

\item{max_vars}{Optional maximum number of visible columns; \code{NULL} derives this
from console width.}

\item{width}{Optional display width; defaults to \code{getOption("width")}.}

\item{show_ci}{One of \code{"yes"} or \code{"no"}.}

\item{title}{Plot title. Default is \code{"Tetrachoric correlation heatmap"}.}

\item{low_color}{Color for the minimum correlation.}

\item{high_color}{Color for the maximum correlation.}

\item{mid_color}{Color for zero correlation.}

\item{value_text_size}{Font size used in tile labels.}

\item{show_value}{Logical; if \code{TRUE} (default), overlay numeric values
on the heatmap tiles.}

\item{object}{An object of class \code{tetrachoric_corr}.}

\item{ci_digits}{Integer; digits for confidence limits in the pairwise
summary.}

\item{p_digits}{Integer; digits for p-values in the pairwise summary.}
}
\value{
If \code{y} is supplied, a numeric scalar with attributes
\code{diagnostics} and \code{thresholds}. Otherwise a symmetric matrix of
class \code{tetrachoric_corr} with attributes \code{method},
\code{description}, \code{package = "matrixCorr"}, \code{diagnostics},
\code{thresholds}, and \code{correct}. When \code{p_value = TRUE}, the
returned object also carries an \code{inference} attribute with elements
\code{estimate}, \code{statistic}, \code{parameter}, \code{p_value}, and
\code{n_obs}. When \code{ci = TRUE}, it also carries a \code{ci} attribute
with elements \code{est}, \code{lwr.ci}, \code{upr.ci}, \code{conf.level},
and \code{ci.method}, plus \code{attr(x, "conf.level")}. Scalar outputs keep
the same point estimate and gain the same metadata only when inference is
requested. In matrix mode, \code{output = "edge_list"} returns a data frame with columns
\code{row}, \code{col}, \code{value}; \code{output = "sparse"} returns a
symmetric sparse matrix.
}
\description{
Computes the tetrachoric correlation for either a pair of binary variables
or all pairwise combinations of binary columns in a matrix/data frame.
}
\details{
The tetrachoric correlation assumes that the observed binary variables arise
by dichotomising latent standard-normal variables. Let
\eqn{Z_1, Z_2 \sim N(0, 1)} with latent correlation \eqn{\rho}, and define
observed binary variables by thresholds \eqn{\tau_1, \tau_2}:
\deqn{
X = \mathbf{1}\{Z_1 > \tau_1\},
\qquad
Y = \mathbf{1}\{Z_2 > \tau_2\}.
}
If the observed \eqn{2 \times 2} table has counts
\eqn{n_{ij}} for \eqn{i,j \in \{0,1\}}, the marginal proportions determine
the thresholds:
\deqn{
\tau_1 = \Phi^{-1}\!\big(P(X = 0)\big),
\qquad
\tau_2 = \Phi^{-1}\!\big(P(Y = 0)\big).
}
The estimator returned here is the maximum-likelihood estimate of the latent
correlation \eqn{\rho}, obtained by maximizing the multinomial log-likelihood
built from the rectangle probabilities of the bivariate normal distribution:
\deqn{
\ell(\rho) = \sum_{i=0}^1 \sum_{j=0}^1 n_{ij}\log \pi_{ij}(\rho;\tau_1,\tau_2),
}
where \eqn{\pi_{ij}} are the four bivariate-normal cell probabilities implied
by \eqn{\rho} and the fixed thresholds. The implementation evaluates the
likelihood over \eqn{\rho \in (-1,1)} by a coarse search followed by Brent
refinement in C++.

The argument \code{correct} adds a continuity correction only to zero-count
cells before threshold estimation and likelihood evaluation. This stabilises
the estimator for sparse tables and mirrors the conventional
\code{correct = 0.5} continuity-correction behaviour used in several
latent-correlation implementations.
When \code{correct = 0} and the observed contingency table contains zero
cells, the fit is non-regular and may be boundary-driven. In those cases the
returned object stores sparse-fit diagnostics, including whether the fit was
classified as \code{boundary} or \code{near_boundary}.

\strong{Assumptions.} The coefficient is appropriate when both observed
binary variables are viewed as thresholded versions of jointly normal latent
variables. The optional p-values and confidence intervals adopt this
latent-normal interpretation and use the same likelihood that defines the
tetrachoric estimate. These inferential quantities are therefore model-based
and should not be interpreted as distribution-free summaries.

\strong{Inference.} When \code{ci = TRUE} or \code{p_value = TRUE}, the
function refits the pairwise tetrachoric model by maximum likelihood and
obtains the observed information matrix numerically in C++. The reported
confidence interval is a Wald interval
\eqn{\hat\rho \pm z_{1-\alpha/2}\operatorname{SE}(\hat\rho)}, and the
reported p-value is from the large-sample Wald \eqn{z}-test for
\eqn{H_0:\rho = 0}. These inferential quantities are only computed when
explicitly requested.

In matrix/data-frame mode, all pairwise tetrachoric correlations are computed
between binary columns. Diagonal entries are \code{1} for non-degenerate
columns and \code{NA} for columns with fewer than two observed levels.
Variable-specific latent thresholds are stored in the \code{thresholds}
attribute, and pairwise sparse-fit diagnostics are stored in
\code{diagnostics}.

\strong{Computational complexity.} For \eqn{p} binary variables, the matrix
path evaluates \eqn{p(p-1)/2} pairwise likelihoods. Each pair uses a
one-dimensional optimisation with negligible memory overhead beyond the
output matrix.
}
\examples{
\dontshow{if (requireNamespace("mnormt", quietly = TRUE)) withAutoprint(\{ # examplesIf}
set.seed(123)
n <- 1000
Sigma <- matrix(c(
  1.00, 0.55, 0.35,
  0.55, 1.00, 0.45,
  0.35, 0.45, 1.00
), 3, 3, byrow = TRUE)

Z <- mnormt::rmnorm(n = n, mean = rep(0, 3), varcov = Sigma)
X <- data.frame(
  item1 = Z[, 1] > stats::qnorm(0.70),
  item2 = Z[, 2] > stats::qnorm(0.60),
  item3 = Z[, 3] > stats::qnorm(0.50)
)

tc <- tetrachoric(X)
print(tc, digits = 3)
summary(tc)
estimate(tc)
tidy(tc)
tc_ci <- tetrachoric(X, ci = TRUE)
ci(tc_ci)
confint(tc_ci)
plot(tc)
tetrachoric(X, output = "edge_list", diag = FALSE)
tetrachoric(X, output = "sparse", threshold = 0.4, diag = FALSE)

# Interactive viewing (requires shiny)
if (interactive() && requireNamespace("shiny", quietly = TRUE)) {
  view_corr_shiny(tc)
}

# latent Pearson correlations used to generate the binary items
round(stats::cor(Z), 2)
\dontshow{\}) # examplesIf}
}
\references{
Pearson, K. (1900). Mathematical contributions to the theory of evolution.
VII. On the correlation of characters not quantitatively measurable.
\emph{Philosophical Transactions of the Royal Society A}, 195, 1-47.

Olsson, U. (1979). Maximum likelihood estimation of the polychoric
correlation coefficient. \emph{Psychometrika}, 44(4), 443-460.
}
\author{
Thiago de Paula Oliveira
}
