Reference · Statistics

stats.correlation

signature
stats.correlation(list, list, str=) -> float

What it does

Pearson's correlation coefficient of two lists of numbers of the same length, from -1 to 1, as Python's statistics.correlation: 1 when the pairs lie on a rising line, -1 on a falling one, 0 when there is no linear relation. The method is "linear" by default; "ranked" gives Spearman's rank correlation, which measures whether the pairs rise together at all, line or not, by correlating their ranks (ties share their average rank).

Examples

let x = [1, 2, 3, 4, 5, 6, 7, 8, 9]let y = [1, 2, 3, 1, 2, 3, 1, 2, 3]let z = [9, 8, 7, 6, 5, 4, 3, 2, 1]print(stats.correlation(x, x), stats.correlation(x, z), stats.correlation(x, y))print(stats.correlation([1, 2, 3, 4], [1, 4, 9, 16]))print(stats.correlation([1, 2, 3, 4], [1, 4, 9, 16], "ranked"))
output
1.0 -1.0 0.316227766016837940.98437403869769721.0

Edge cases

print(stats.correlation([1, 2, 3, 4, 5], [1, 2, 3, 4, 100]))print(stats.correlation([1, 2, 3, 4, 5], [1, 2, 3, 4, 100], "ranked"))print(stats.correlation([1, 2, 2, 3], [1, 3, 2, 4], "ranked"), stats.correlation([1, 2], [5, 3.5], null))
output
0.72499943359441371.00.9486832980505138 -1.0

Errors

A constant list is a runtime error, not an error value, since its correlation is not defined. So are lists of different lengths, fewer than two points, a method other than "linear" or "ranked", and an item that is not a number.

this one fails
print(stats.correlation([1, 2, 3], [5, 5, 5]))
output
line 1: `stats.correlation`: at least one of the inputs is constant
this one fails
print(stats.correlation([1, 2, 3], [1, 2, 3], "spearman"))
output
line 1: `stats.correlation`: unknown method "spearman" (linear or ranked)
this one fails
print(stats.correlation([1], [1]))
output
line 1: `stats.correlation` requires at least two data points

Chaining

In a pipeline the first list comes first and the second is the argument:

let ads = [10, 20, 30, 40]let sales = [110, 190, 310, 390]print(ads | stats.correlation(sales) | round(4))print(ads | stats.correlation(sales, "ranked"))
output
0.99651.0

See also

stats.covariance, stats.linear_regression, stats.rank

Thread
9Useful? Like it, or add to its thread below.

Thread 0 posts

On stats.correlation(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo