Association and Correlation in Statistics
Studying association means asking how the variations, orderings or frequencies of two characteristics relate to one another. The answer depends on what we observe, how we measure it and how the data were obtained: a linear relationship between temperature and industrial conversion is not quite the same problem as comparing heart attacks across two arms of a clinical trial.
This article develops those distinctions through definitions, explained equations and reproducible calculations in R. It moves from covariance to Pearson, Spearman and Kendall correlations, then to contingency tables, association tests and effect measures for a binary outcome. At each stage, description of the data, uncertainty in estimation and the scientific scope of a conclusion remain distinct.
01 · The scientific question comes before the coefficient
A statistical association is a regularity in the joint distribution of variables. Correlation summarizes particular aspects of that regularity. Causation additionally requires an account of what would happen to an outcome if an intervention changed the exposure or treatment. Selecting a coefficient does not, by itself, answer that third question.
Before calculating, identify the observational unit, measurement scale, target population, observation period and study design. Two measurements on one person form a pair; twenty measurements on the same person are not equivalent to twenty independent people. Ordered categories, numerical magnitudes and nominal categories also call for different analyses.
| Question | Initial tool | Limit of the answer |
|---|---|---|
| Is there a linear association between numerical quantities? | Pearson and a scatterplot | Curved relationships may be missed. |
| Do values tend to preserve an increasing or decreasing order? | Spearman or Kendall | A rank summary may miss nonmonotonic patterns. |
| Do event frequencies differ between groups? | Contingency table, risks and comparative measures | The design determines which risks and effects are identifiable. |
| Does treatment cause a difference? | Appropriate causal design and analysis | Association or a p-value alone is insufficient. |
The estimand is the population quantity of interest; an estimator is a rule for calculating it from a sample; an estimate is the resulting value. A test statistic is constructed to evaluate compatibility with a hypothesis. For example, ρ is a population correlation, r is its estimator and t is the statistic used in the classical zero-correlation test.
02 · Covariance and Pearson: from joint variation to standardization
Centering each observation around its mean identifies whether it lies above or below average. The product of the two deviations is positive when their signs agree and negative when their signs differ. The sum combines these contributions. Dividing by n − 1 gives the usual sample covariance, unbiased under independent, identically distributed sampling with finite moments.
Covariance retains units: when X is measured in degrees and Y in percentage points, the units are their product. Its magnitude therefore does not supply a universal scale of association strength.
Standardization removes units and places r between −1 and 1. Its sign indicates direction, while its absolute value summarizes linear alignment. The endpoints correspond to a perfect affine relationship in the sample. A constant variable has zero standard deviation, making the coefficient undefined.
Pearson can be used with quantitative interval or ratio variables; calculating it does not require normality. It is not a proportion of people or a general percentage of shared variation. In simple linear regression with an intercept and the same observations, R² = r², but that identity has this specific context.
Cor(a + bX, c + dY) = sign(bd) Cor(X,Y), b,d ≠ 0(3)
Adding constants does not change association. Multiplication by positive factors changes covariance but preserves correlation; reversing the sign of one variable reverses Pearson’s sign. Invariance to changes in measurement units is therefore distinct from invariance to arbitrary transformations.
03 · Zero correlation, dependence and geometry
If two variables are independent and have finite, positive variances, their population correlation is zero. The converse is false. Let X be uniform on [−1,1] and Y = X²: by symmetry, E[X] = E[X³] = 0, and hence Cov(X,Y) = 0, although knowing X determines Y exactly. Absence of linear association does not remove dependence.
Geometrically, r is the cosine of the angle between the centered sample vectors. If r = 0, these vectors are orthogonal. Sample orthogonality is not probabilistic independence and should not be confused with linear independence of vectors. Under a jointly bivariate normal model, zero population correlation does imply independence, but separately normal marginal distributions do not suffice.
[12]Inspect the points before choosing a coefficient: linearity, monotonicity, influential values, clusters and restricted ranges can lead to different interpretations. None of the three coefficients discussed here is a universal detector of dependence.
04 · Spearman: correlation between ranks
Spearman replaces magnitudes with ordered positions. A strictly increasing relationship preserves the orderings and reaches +1 when the ranks agree perfectly; a decreasing relationship reaches −1 when they are perfectly reversed. Because it uses order, a strictly increasing transformation of a variable preserves the coefficient. A monotonic association can be curved: increasing X may accompany increasingly large increments in Y.
In the shortcut formula, di is the difference between the two ranks of observation i. Ordering discrepancies reduce the coefficient from its maximum. With ties, assign average ranks and calculate Pearson on those ranks; do not automatically apply the shortcut. Rank methods reduce the influence of extreme magnitudes, but do not eliminate every problem of data, design or interpretation.
[1]05 · Kendall: concordance, discordance and ties
With n observations there are n(n − 1)/2 pairs of observations. A pair is concordant when the observation higher on X is also higher on Y, and discordant when this ordering is reversed. Equality requires specific treatment.
τb = C − D√[(C + D + TX)(C + D + TY)](6)
C and D count concordant and discordant pairs; TX counts pairs tied only on X, and TY those tied only on Y. Pairs tied on both variables contribute to none of these four counts. Without ties, τ can be interpreted as the difference between the probabilities of concordance and discordance for a random pair. The τb version normalizes for ties and is calculated by cor(..., method = "kendall").
| Observation | X | Y | Rank X | Rank Y |
|---|---|---|---|---|
| 1 | 1 | 1 | 1 | 1 |
| 2 | 2 | 3 | 2.5 | 3 |
| 3 | 2 | 2 | 2.5 | 2 |
| 4 | 4 | 4 | 4 | 4 |
Here C = 5, D = 0, TX = 1 and TY = 0. Thus τb = 5/√30 ≈ 0.912871 and Spearman ≈ 0.948683. The numbers differ because the coefficients summarize different objects; applying identical strength thresholds to both requires justification.
[3]06 · Choosing a measure and specifying its assumptions
| Measure | What it summarizes | What to inspect |
|---|---|---|
| Pearson | Linear association between magnitudes | Scatterplot, influential points, observed range and inferential model. |
| Spearman | Rank association, sensitive to monotonicity | Meaningful ordering, ties and p-value calculation. |
| Kendall | Balance of concordance and discordance | Ties, the version of τ and the test approximation. |
The decision should follow the substantive question and anticipated pattern. An isolated normality test does not automatically determine which coefficient makes sense. Pearson remains a calculable linear summary with nonnormal data; what may fail is classical inference used without regard to its model.
The exact Pearson t test under zero correlation is justified for independent pairs from the bivariate normal model. In the equivalent fixed-X regression formulation, the model uses independent normal errors with constant variance. These are related frameworks; neither reduces to checking the normality of Y alone. Rank methods also require a sampling framework and independent observational units for their ordinary tests.
Repeated measurements, clusters, time series and complex selection require procedures that respect that structure. A coefficient calculated while ignoring it may describe the points without making its ordinary p-value valid.
07 · Complete data and manual calculation in R
Two teaching contexts are retained: conditions in a vinylation process and association between animal activity and metabolism. The industrial question concerns how temperature and pressure relate to percentage conversion; those associations alone do not identify optimal settings for a multivariable process.
# Illustrative data, not the missing original CSV files.
vinylation <- data.frame(
temperature = c(60,65,70,75,80,85,90,95),
pressure = c(2,4,3,5,4,6,5,7),
conversion = c(22,29,27,38,43,41,52,56)
)
activity <- data.frame(
activity_index = c(2,3,3,4,5,5,6,7,7,8,9,9,10,11,11,12,13,14,14,15),
metabolic_rate = c(12,14,13,15,18,16,19,21,20,22,25,23,26,29,27,30,31,34,32,35)
)
# Retain complete, finite pairs; record what was removed.
prepare_pairs <- function(x, y) {
stopifnot(is.numeric(x), is.numeric(y), length(x) == length(y))
ok <- is.finite(x) & is.finite(y)
x <- x[ok]; y <- y[ok]
if (length(x) < 4L) stop("At least four complete pairs required.")
if (sd(x) == 0 || sd(y) == 0) stop("A variable is constant.")
list(x = x, y = y, n = length(x), removed = sum(!ok))
}
pairs_xy <- prepare_pairs(vinylation$temperature, vinylation$conversion)
x <- pairs_xy$x; y <- pairs_xy$y; n <- pairs_xy$n
pairs_xy[c("n", "removed")]
The sample size n is obtained after selecting valid pairs. The function reports excluded observations and prevents correlations involving constant variables. Complete-case deletion is an analytical decision, not a general remedy for missing-data bias: why observations are missing still matters.
s_xy <- sum((x - mean(x)) * (y - mean(y))) / (n - 1)
r <- s_xy / (sd(x) * sd(y))
c(covariance = s_xy, pearson = r)
stopifnot(isTRUE(all.equal(s_xy, cov(x, y))),
isTRUE(all.equal(r, cor(x, y))))
S <- cov(vinylation)
S # Variances on the diagonal.
cor(vinylation) # Pearson by default.
cor(vinylation, method = "spearman")
cor(vinylation, method = "kendall")
stopifnot(isTRUE(all.equal(cov2cor(S), cor(vinylation))))
In the industrial example, sXY = 142.857143 and r = 0.971057. The eight illustrative points display pronounced positive alignment; the small sample limits assessment of assumptions. In a covariance matrix, variances occupy the diagonal and covariances the off-diagonal positions. A correlation matrix has diagonal entries of 1 for nonconstant variables.
When comparing matrices with missing values, prefer a common, documented sample. Pairwise deletion may use different observations for each entry and yield a matrix that is not positive semidefinite.
rx <- rank(x, ties.method = "average")
ry <- rank(y, ties.method = "average")
rho_s <- cor(rx, ry)
stopifnot(isTRUE(all.equal(rho_s, cor(x, y, method = "spearman"))))
# Formula without ties: use only when neither variable has ties.
if (!anyDuplicated(x) && !anyDuplicated(y)) {
rho_short <- 1 - 6 * sum((rx - ry)^2) / (n * (n^2 - 1))
stopifnot(isTRUE(all.equal(rho_s, rho_short)))
}
kendall_manual <- function(x, y) {
ij <- combn(seq_along(x), 2)
sx <- sign(x[ij[1, ]] - x[ij[2, ]])
sy <- sign(y[ij[1, ]] - y[ij[2, ]])
C <- sum(sx * sy > 0); D <- sum(sx * sy < 0)
Tx <- sum(sx == 0 & sy != 0) # Tied only on x.
Ty <- sum(sy == 0 & sx != 0) # Tied only on y.
den <- sqrt((C + D + Tx) * (C + D + Ty))
if (den == 0) return(NA_real_)
(C - D) / den
}
tau_b <- kendall_manual(x, y)
stopifnot(isTRUE(all.equal(tau_b, cor(x, y, method = "kendall"))))
c(pearson = r, spearman = rho_s, kendall = tau_b)
# Small, tied example: average ranks and pair counts are inspectable.
u <- c(1, 2, 2, 4); v <- c(1, 3, 2, 4)
data.frame(u, v, rank_u = rank(u), rank_v = rank(v))
c(spearman = cor(u, v, method = "spearman"),
kendall = kendall_manual(u, v))
The same eight pairs yield Spearman = 0.952381 and Kendall = 0.857143. The code makes ranks and pair counts explicit and checks manual formulas against R functions. Automatic calculations do not replace understanding of the estimated object.
08 · Inference: hypotheses, p-values and decisions
t = r √[n − 21 − r²], df = n − 2(7)
The sample supplies r; the test evaluates a statement about ρ. Under the classical assumptions and H0, the statistic follows Student’s t distribution with n − 2 degrees of freedom. A two-sided alternative combines both tail probabilities, which is why the code uses the absolute value of t.
The p-value is the probability, under the specified null model, of obtaining a statistic at least as extreme as the observed one. It is not P(H0 | data), the probability that the result is due to chance, or the effect size. A significance level α is fixed as part of the procedure: a Type I error is rejection of a true null hypothesis. The observed p-value is not a personalized probability of having made that error.
If the prespecified criterion is p ≤ α, reject H0 when it holds. Otherwise, do not reject: insufficient evidence does not prove an exactly zero correlation. Nor does a significant result demonstrate a strong association, clinical importance or causality.
[5]Rank tests distinguish exact procedures from approximations. Ties affect which calculations are available; exact = FALSE explicitly requests an approximation in examples containing ties. A t transformation of Spearman should not be presented as exact for every sample. In R, even the option named exact for Spearman can use approximations depending on sample size.
09 · Confidence intervals: Fisher’s transformation
SE(zr) ≈ 1√(n − 3)(8)
The coefficient r is bounded and its sampling distribution may be asymmetric, particularly near ±1. Fisher maps it to an unbounded scale with an approximately normal distribution and a variance approximately stable across values of ρ. The standard error shown belongs to that transformed scale.
CIρ = [tanh(Lz), tanh(Uz)](9)
Transform first, construct the interval second, and invert its endpoints third. The bounds then return to the correlation scale. The approximation requires n > 3 and |r| < 1 and remains sensitive to the model and sample size. A 95% interval is interpreted through the procedure’s coverage across repeated samples, rather than a 95% frequentist probability assigned to the fixed parameter after observing the data.
[11]if (abs(r) >= 1) stop("Perfect correlation: inspect the data separately.")
t_stat <- r * sqrt((n - 2) / (1 - r^2))
p_two <- 2 * pt(-abs(t_stat), df = n - 2)
alpha <- 0.05
z_r <- atanh(r)
ci_r <- tanh(z_r + c(-1, 1) * qnorm(1 - alpha/2) / sqrt(n - 3))
pearson_test <- cor.test(x, y, method = "pearson", conf.level = 1-alpha)
c(t = t_stat, df = n-2, p = p_two, lower = ci_r[1], upper = ci_r[2])
stopifnot(isTRUE(all.equal(p_two, pearson_test$p.value)),
isTRUE(all.equal(as.numeric(ci_r), as.numeric(pearson_test$conf.int))))
# Ties: explicitly request approximations rather than exact p-values.
cor.test(activity$activity_index, activity$metabolic_rate,
method = "pearson")
cor.test(activity$activity_index, activity$metabolic_rate,
method = "spearman", exact = FALSE)
cor.test(activity$activity_index, activity$metabolic_rate,
method = "kendall", exact = FALSE)
# Quantile comparison, not a correlation-confidence-interval recipe.
cbind(df = c(6, 30, 1000), t975 = qt(.975, c(6, 30, 1000)),
normal975 = qnorm(.975))
For the industrial data: t = 9.958592, df = 6, p ≈ 0.00005931 and Fisher’s approximate 95% CI ≈ [0.843728, 0.994925]. These are illustrative results under the stated model. The code compares the manual calculation with cor.test(); its ordinary intervals are supplied for Pearson, not automatically for the other two measures.
The biological example yields Pearson ≈ 0.994995, Spearman ≈ 0.997742 and Kendall ≈ 0.984084. It is a constructed series with pronounced association, not an estimate about actual animals. Convergence of t quantiles toward normal quantiles as degrees of freedom grow is a separate fact: it does not justify constructing an interval for ρ as r ± a quantile times the denominator of the t statistic.
10 · Scatterplots, regression and diagnostics
old_par <- par(mfrow = c(2, 2))
plot(conversion ~ temperature, data = vinylation,
xlab = "Temperature (illustrative units)", ylab = "Conversion (%)", pch = 19)
fit_temp <- lm(conversion ~ temperature, data = vinylation)
abline(fit_temp, col = "#8b4513", lwd = 2)
plot(conversion ~ pressure, data = vinylation,
xlab = "Pressure (illustrative units)", ylab = "Conversion (%)", pch = 19)
fit_pressure <- lm(conversion ~ pressure, data = vinylation)
abline(fit_pressure, col = "#8b4513", lwd = 2)
plot(fitted(fit_temp), residuals(fit_temp),
xlab = "Fitted conversion", ylab = "Residual", pch = 19)
abline(h = 0, lty = 2)
qqnorm(residuals(fit_temp)); qqline(residuals(fit_temp))
par(old_par)
# y = x^2: strong dependence, zero sample Pearson on a symmetric grid.
grid_x <- seq(-2, 2, length.out = 101)
c(pearson = cor(grid_x, grid_x^2),
spearman = cor(grid_x, grid_x^2, method = "spearman"))
The formula conversion ~ temperature places conversion on the response side; the model and plot preserve that orientation. Pearson is symmetric in X and Y, whereas regression is not: exchanging the response changes the question and generally the fitted line.
A simple linear model is Yi = β0 + β1Xi + εi. The intercept is included by default; removing it requires justification and changes identities such as R² = r². More generally, “linear” refers to parameters: lm(y ~ x + I(x^2)) remains linear in its coefficients although it describes a curve.
WLS: minimize ∑ wiei²(10)
Residuals ei are differences between observed and fitted responses. Weighted least squares uses supplied weights; it does not automatically estimate those weights as part of this minimization. When variances are known up to a common factor, inverse-variance weights are commonly used. Integer frequency weights or grouped means require care with within-group variation and degrees of freedom.
lm() also accepts a response matrix and fits each column; this does not turn weights into independent replicates. Residual inspection, design and substantive knowledge matter more than the mere presence of a straight line drawn over the data.
11 · From magnitudes to categories: contingency tables
A contingency table organizes counts of units across categories. For a two-arm trial with a binary outcome, use rows for treatment and columns for event status. Each participant contributes to one cell, and follow-up remains comparable.
| Group | Event | No event | Total |
|---|---|---|---|
| Illustrative aspirin | 20 | 1,980 | 2,000 |
| Illustrative placebo | 40 | 1,960 | 2,000 |
| Total | 60 | 3,940 | 4,000 |
With this orientation, prop.table(trial, 1) calculates outcome proportions within each arm. By contrast, prop.table(trial, 2) calculates group composition within each outcome. With no margin argument it gives joint proportions. None of these instructions alone calculates a relative risk.
The observed frequencies Oij are the data. Under independence, expected frequencies follow from the margins:
ni+ is row i’s total, n+j is column j’s total, and N is the overall total. The formula applies the marginal outcome proportion to each row. Here H0 implies 30 events and 1,970 non-events per arm. Expected counts can be fractional: they are theoretical averages, not additional participants.
12 · Chi-square, Yates and Fisher: what is being tested?
df = (F − 1)(C − 1)(12)
Squaring prevents positive and negative discrepancies from cancelling; division by Eij scales each discrepancy relative to its expected count. F and C denote the numbers of rows and columns. Under H0 and suitable approximation conditions, X² is compared with a chi-square distribution. This is not a correlation between numerical codes assigned to categories.
The χ²ν distribution is the distribution of a sum of squared independent standard normal variables. It appears in goodness-of-fit tests, independence tests and, under normality, variance inference. For the table, the statistic has an approximate chi-square distribution; the distribution’s definition does not make every sum of squares exactly chi-square.
# Hypothetical trial: 2,000 participants per arm, same follow-up.
# These counts are not results of the historical aspirin trial.
trial <- matrix(c(20, 1980, 40, 1960), nrow = 2, byrow = TRUE,
dimnames = list(group = c("Aspirin", "Placebo"),
outcome = c("Event", "No_event")))
addmargins(trial)
prop.table(trial, margin = 1) # Outcome proportions within each arm.
prop.table(trial, margin = 2) # Arm composition within each outcome.
addmargins(prop.table(trial)) # Joint proportions and marginal totals.
# Equivalent representation with aggregated frequencies.
trial_long <- data.frame(
group = factor(c("Aspirin", "Aspirin", "Placebo", "Placebo"),
levels = c("Aspirin", "Placebo")),
outcome = factor(c("Event", "No_event", "Event", "No_event"),
levels = c("Event", "No_event")),
freq = c(20, 1980, 40, 1960))
from_long <- xtabs(freq ~ group + outcome, data = trial_long)
stopifnot(all(from_long == trial))
expected <- outer(rowSums(trial), colSums(trial)) / sum(trial)
contributions <- (trial - expected)^2 / expected
X2 <- sum(contributions)
df_chi <- (nrow(trial)-1) * (ncol(trial)-1)
p_chi <- pchisq(X2, df = df_chi, lower.tail = FALSE)
chi_test <- chisq.test(trial, correct = FALSE)
expected; contributions
c(X2 = X2, df = df_chi, p = p_chi)
stopifnot(isTRUE(all.equal(X2, unname(chi_test$statistic))),
isTRUE(all.equal(p_chi, chi_test$p.value)))
# Sensitivity comparison; choose the primary method before examining p.
c(pearson = chi_test$p.value,
yates = chisq.test(trial, correct = TRUE)$p.value,
fisher = fisher.test(trial)$p.value)
fisher.test(trial) # Conditional OR estimate and confidence interval.
The example gives X² ≈ 6.768190, df = 1 and p ≈ 0.009280 without correction. Yates gives p ≈ 0.013455 and two-sided Fisher p ≈ 0.012806. All three reject at 0.05 here. The comparison describes procedural sensitivity; it does not license choosing whichever p-value is convenient after seeing the results.
R applies Yates by default to 2 × 2 tables. Its modification reduces absolute discrepancies before squaring and can make the test conservative. Small expected counts signal a need to inspect the approximation, rather than a universal instruction to apply Yates. Consider the design, table configuration and exact or simulated alternatives.
[6][13]Fisher constructs a conditional distribution given the margins. Under the null hypothesis OR = 1, the first-cell count A follows a hypergeometric distribution:
n1 and n0 are arm sizes; m is the event total and N = n1 + n0. “binom(n,k)” counts ways of selecting k elements from n. The numerator allocates m events across the arms, while the denominator counts all compatible allocations. In this parameterization E[A] = n1m/N and Var(A) = n1(m/N)(1 − m/N)(N − n1)/(N − 1).
The hypergeometric distribution describes allocations without replacement within a finite total; a binomial assumes independent trials with constant probability. A small sampling fraction can make a binomial approximation useful. Conditioning on margins does not mean that both were fixed by design: a trial’s total event count is usually random. Fisher supplies conditional inference, not the only possible inference.
[7]Large sparse tables may use conditional simulation, documenting the number of replicates and random seed. If observations are paired, such as before-and-after outcomes on the same people, ordinary independence tests fail to respect the design; for paired binary outcomes, consider McNemar’s test.
13 · Risk, odds and effect size
Write the table as (a,b) in the first row and (c,d) in the second: treatment events and non-events, followed by control events and non-events. Each measure answers a different question.
| Measure | Definition | Interpretation |
|---|---|---|
| Risk | p₁ = a/(a+b); p₀ = c/(c+d) | Event probability during the specified follow-up. |
| Odds | p/(1−p) | Events relative to non-events. |
| Relative risk | RR = p₁/p₀ | Multiplicative comparison of risks. |
| Odds ratio | OR = (a/b)/(c/d) = ad/(bc) | Multiplicative comparison of odds. |
| Risk difference | RD = p₁−p₀ | Absolute change in probability. |
| Absolute risk reduction | ARR = p₀−p₁ | Absolute decrease for an adverse event. |
| Relative risk reduction | RRR = 1−RR | Proportional decrease relative to control risk. |
| Number needed to treat | NNT = 1/ARR, if ARR > 0 | People treated per adverse event prevented over the period. |
With the illustrative counts, p1 = 1% and p0 = 2%: 10 versus 20 events per thousand participants. RR = 0.50, OR ≈ 0.494949, ARR = 0.01 and RRR = 50%. The absolute reduction is one percentage point, not fifty points. Estimated NNT is 100 over the assumed follow-up, provided a causal interpretation is justified.
Multiplying odds by one thousand compares events with one thousand non-events; to express events per thousand participants, multiply risk by one thousand. OR approximates RR when risks in both groups are small, but may differ substantially for common outcomes. The odds ratio can be used in frequentist or Bayesian inference; its definition belongs exclusively to neither framework.
[8]An effect size quantitatively reflects the magnitude of a phenomenon relevant to a question. It may be a correlation, difference or ratio. The same p-value can accompany different magnitudes; a similar magnitude can have very different uncertainty depending on study size and quality. Epistemological relevance and the mathematical properties of a measure should be considered together.
[4]CIOR = exp{ln(OR) ± z · √[1/a + 1/b + 1/c + 1/d]}(14)
These approximate intervals use the logarithmic scale because positive ratios often have asymmetric distributions. For RD, an unpooled Wald approximation is shown, with SE = √[p1(1−p1)/n1 + p0(1−p0)/n0]. These are transparent teaching methods, not universal solutions for sparse counts or zero cells; appropriate alternatives, such as score or exact methods depending on the measure, are needed in those situations.
a <- trial["Aspirin", "Event"]; b <- trial["Aspirin", "No_event"]
c0 <- trial["Placebo", "Event"]; d <- trial["Placebo", "No_event"]
n1 <- a+b; n0 <- c0+d
p1 <- a/n1; p0 <- c0/n0
RR <- p1/p0; OR <- (a*d)/(b*c0)
RD <- p1-p0; ARR <- p0-p1; RRR <- 1-RR
# Large-sample log intervals: all four counts must be positive here.
stopifnot(all(trial > 0))
zcrit <- qnorm(.975)
se_log_RR <- sqrt(1/a - 1/n1 + 1/c0 - 1/n0)
se_log_OR <- sqrt(1/a + 1/b + 1/c0 + 1/d)
ci_RR <- exp(log(RR) + c(-1, 1)*zcrit*se_log_RR)
ci_OR <- exp(log(OR) + c(-1, 1)*zcrit*se_log_OR)
se_RD <- sqrt(p1*(1-p1)/n1 + p0*(1-p0)/n0)
ci_RD <- RD + c(-1, 1)*zcrit*se_RD # Unpooled Wald approximation.
ci_ARR <- -rev(ci_RD)
NNT <- if (ARR > 0) 1/ARR else NA_real_
ci_NNT <- if (all(ci_ARR > 0)) 1/rev(ci_ARR) else c(NA_real_, NA_real_)
rbind(RR = c(RR, ci_RR), OR = c(OR, ci_OR), RD = c(RD, ci_RD))
c(ARR = ARR, RRR = RRR, NNT = NNT)
ci_NNT
| Measure | Estimate | Approximate 95% CI |
|---|---|---|
| RR | 0.500000 | [0.293372, 0.852161] |
| Sample OR | 0.494949 | [0.288322, 0.849659] |
| RD | −0.010000 | [−0.017527, −0.002473] |
| NNT | 100 | [57.05, 404.43] before rounding |
The NNT interval inverts endpoints of a positive ARR interval; if that interval crosses zero, inversion passes through infinity and should not be reported as an ordinary finite interval. NNT is commonly rounded upward when communicating whole people. The conditional OR estimate and interval returned by fisher.test() use a different procedure and can differ from the sample OR ad/bc and its log interval.
14 · What a clinical trial actually adds
Randomization seeks to make treatment assignment independent of prognostic characteristics; allocation concealment protects recruitment and blinding reduces certain subsequent influences. These are distinct mechanisms. The protocol should define population, outcome, follow-up, comparison and analysis before results are observed.
Intention-to-treat analysis retains people in their assigned group, directing estimation toward the effect of assignment. It does not remove missing-data or adherence problems. Loss to follow-up, competing events, protocol deviations and multiple outcomes require specific attention. A 2 × 2 table can oversimplify a study with differing follow-up times or censoring.
[9]A favorable relative effect must be read alongside baseline risk, absolute difference, adverse events and the studied population. This example teaches statistical analysis of a hypothetical trial; by itself, it does not establish an individual clinical indication or justify automatic extrapolation from one population to another.
15 · Reporting results without losing their meaning
A clear report identifies the question and design; describes variables and units; presents the plot or table; states method, effective sample size and handling of ties or missing data; reports the estimate, interval and p-value when appropriate; and delimits interpretation.
The strength of a conclusion depends on the correspondence between question, design, measure and inference.
For the industrial series: “Eight illustrative pairs yielded r = 0.9711, with Fisher’s approximate 95% CI [0.8437, 0.9949]; the classical two-sided test gave p ≈ 0.0000593. This describes positive linear association under the specified model and does not identify a causal effect of temperature.”
For the constructed trial: “Over an assumed common follow-up, the event occurred in 20/2,000 and 40/2,000 participants; RR = 0.50 with approximate log-scale 95% CI [0.2934, 0.8522], and a risk difference of −1 percentage point.” Absolute magnitude remains necessary even when a p-value is reported.
When exploring many correlations, distinguish exploratory from confirmatory analysis and consider multiplicity. Do not select the coefficient, test direction or sample solely to obtain significance.
16 · Reproducibility and references
Run the R blocks in reading order in a fresh session, using base R and the stats package included with a standard installation. No external files, personal paths or additional packages are required. Object names and code labels remain identical across languages to facilitate comparison.
# Numerical checks of the transparent examples.
stopifnot(n == 8L, abs(s_xy - 1000/7) < 1e-10,
abs(RR - 0.5) < 1e-12, abs(ARR - 0.01) < 1e-12,
abs(X2 - 6.7681895093) < 1e-8,
abs(kendall_manual(u, v) - 5/sqrt(30)) < 1e-12)
sessionInfo()
Numerical checks compare manual formulas with built-in functions. sessionInfo() records version and environment, helping document implementation differences. Printed figures are rounded; calculations retain numerical precision.
The following bibliography supports further study of the measures and verification of R’s behavior. The original post date is retained as an editorial reference; this revision develops and corrects its content.
References and documentation
- R Core Team. Correlation, Variance and Covariance; cor(), cov(), cov2cor().
- R Core Team. Test for Association/Correlation Between Paired Samples; cor.test().
- Taylor, J. M. G. (1987). Kendall’s and Spearman’s Correlation Coefficients in the Presence of a Blocking Variable. Biometrics, 43, 409–416.
- Kelley, K., & Preacher, K. J. (2012). On effect size. Psychological Methods, 17(2), 137–152. DOI: 10.1037/a0028086.
- American Statistical Association (2016). Statement on Statistical Significance and P-Values: six principles.
- R Core Team. Pearson’s Chi-squared Test for Count Data; chisq.test().
- R Core Team. Fisher’s Exact Test for Count Data; fisher.test().
- Dicker, R. C. Analyzing and Interpreting Data. The CDC Field Epidemiology Manual, chapter 8.
- Steering Committee of the Physicians’ Health Study Research Group (1989). Final report on the aspirin component of the ongoing Physicians’ Health Study. New England Journal of Medicine, 321, 129–135. DOI: 10.1056/NEJM198907203210301.
- R Core Team. Fitting Linear Models; lm().
- Pennsylvania State University. STAT 509, Lesson 7: Early Phase Studies; correlation and Fisher transformation.
- Pennsylvania State University. STAT 414, Lesson 18: The Correlation Coefficient.
- Grizzle, J. E. (1967). Continuity Correction in the χ²-Test for 2 × 2 Tables. The American Statistician, 21(4), 28–32. DOI: 10.2307/2682103.


Leave a Comment/Deja un Comentario