0
0
R-programmingHow-ToBeginner · 3 min read

How to Create Confidence Interval r in R: Simple Guide

To create a confidence interval for the correlation coefficient r in R, use the cor.test() function which returns the correlation and its confidence interval. This function works for Pearson, Spearman, or Kendall correlations and provides the interval in the output list under $conf.int.
📐

Syntax

The main function to create a confidence interval for correlation r in R is cor.test(x, y, method = "pearson", conf.level = 0.95).

  • x, y: numeric vectors of data points.
  • method: type of correlation - "pearson" (default), "spearman", or "kendall".
  • conf.level: confidence level for the interval, default is 0.95 (95%).

The result includes estimate for correlation and conf.int for the confidence interval.

r
cor.test(x, y, method = "pearson", conf.level = 0.95)
💻

Example

This example shows how to calculate the Pearson correlation and its 95% confidence interval between two numeric vectors.

r
x <- c(1, 2, 3, 4, 5)
y <- c(2, 4, 6, 8, 10)
result <- cor.test(x, y, method = "pearson", conf.level = 0.95)
result$estimate
result$conf.int
Output
[1] 1 [1] 1 1
⚠️

Common Pitfalls

Common mistakes when creating confidence intervals for correlation in R include:

  • Using cor() instead of cor.test(). The cor() function only calculates the correlation coefficient without confidence intervals.
  • Not checking for missing values in data vectors, which can cause errors or incorrect results.
  • Assuming confidence intervals are always symmetric; for small samples, intervals may be asymmetric.
r
## Wrong: cor() does not give confidence interval
cor(x, y)

## Right: cor.test() gives confidence interval
cor.test(x, y)$conf.int
📊

Quick Reference

FunctionPurposeKey ArgumentOutput
cor.test()Calculate correlation and confidence intervalx, y, method, conf.levelList with estimate and conf.int
cor()Calculate correlation coefficient onlyx, y, methodNumeric correlation value

Key Takeaways

Use cor.test() to get correlation and its confidence interval in R.
Set conf.level to adjust the confidence interval percentage (default 95%).
cor() only calculates correlation without confidence intervals.
Check your data for missing values before running cor.test().
Confidence intervals may be asymmetric for small sample sizes.