Python's statistics.correlation in TypeScript

✓ Verified: Python 3.12
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.
Rosetta Stone: python/prod

How to use

Install via yarn add locutus and import: import { correlation } from 'locutus/python/statistics/correlation'.

Or with CommonJS: const { correlation } = require('locutus/python/statistics/correlation')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1correlation([1, 2, 3], [1, 5, 7])0.9819805060619659
2correlation([1, 2, 3], [7, 5, 3])-1
3correlation([1, 2, 3], [3, 2, 1], 'ranked')-1

Notes

  • Returns Pearson correlation by default and supports Python’s ranked mode for Spearman correlation.

Dependencies

This function uses the following Locutus functions:

Here's what our current TypeScript equivalent to Python's statistics.correlation looks like.

import { assertStatisticsArray, sumProducts, toStatisticNumber } from '../_helpers/_statistics.ts'

export function correlation(x: unknown, y: unknown, method: 'linear' | 'ranked' = 'linear'): number {
// discuss at: https://locutus.io/python/statistics/correlation/
// parity verified: Python 3.12
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Returns Pearson correlation by default and supports Python's ranked mode for Spearman correlation.
// example 1: correlation([1, 2, 3], [1, 5, 7])
// returns 1: 0.9819805060619659
// example 2: correlation([1, 2, 3], [7, 5, 3])
// returns 2: -1
// example 3: correlation([1, 2, 3], [3, 2, 1], 'ranked')
// returns 3: -1

const left = assertStatisticsArray(x, 'correlation').map((value) => toStatisticNumber(value, 'correlation'))
const right = assertStatisticsArray(y, 'correlation').map((value) => toStatisticNumber(value, 'correlation'))

const n = left.length
if (right.length !== n) {
throw new Error('correlation requires that both inputs have same number of data points')
}
if (n < 2) {
throw new Error('correlation requires at least two data points')
}
if (method !== 'linear' && method !== 'ranked') {
throw new TypeError(`Unknown method: '${String(method)}'`)
}

const xValues = method === 'ranked' ? rankValues(left) : centerValues(left)
const yValues = method === 'ranked' ? rankValues(right) : centerValues(right)

const sxy = sumProducts(xValues, yValues)
const sxx = sumProducts(xValues, xValues)
const syy = sumProducts(yValues, yValues)
const denominator = Math.sqrt(sxx * syy)
if (denominator === 0) {
throw new Error('at least one of the inputs is constant')
}

return sxy / denominator
}

function centerValues(values: number[]): number[] {
const mean = values.reduce((sum, value) => sum + value, 0) / values.length
return values.map((value) => value - mean)
}

function rankValues(values: number[]): number[] {
const n = values.length
const start = (n - 1) / -2
const indexed = values.map((value, index) => ({ value, index })).sort((a, b) => a.value - b.value)
const ranks = new Array<number>(n)

let position = 0
while (position < indexed.length) {
let end = position + 1
while (end < indexed.length && indexed[end]?.value === indexed[position]?.value) {
end += 1
}
const averageRank = start + (position + end - 1) / 2
for (let cursor = position; cursor < end; cursor += 1) {
const entry = indexed[cursor]
if (entry) {
ranks[entry.index] = averageRank
}
}
position = end
}

return ranks
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


Help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.

« More Python statistics functions


Star