Created
January 27, 2021 22:30
-
-
Save chrispahm/8f499c83eb59cb30526a09e0475bf2bf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Source: https://stats.stackexchange.com/questions/83826/is-a-weighted-r2-in-robust-linear-model-meaningful-for-goodness-of-fit-analys/375752#375752 | |
// Article: Willet and Singer (1988): https://gseacademic.harvard.edu/~willetjo/pdf%20files/Willett_Singer_AS88.pdf | |
function weightedRsquared(x, func, weights) { | |
if (!weights) weights = x.map(v => 1); | |
// Compute the weighted average y value for the actual | |
// data set in order to compute the | |
// _total sum of squares_ | |
let sum = 0; | |
for (let i = 0; i < x.length; i++) { | |
sum += x[i][1] * weights[i]; | |
} | |
let sumOfWeights = 0; | |
for (let j = 0; j < x.length; j++) { | |
sumOfWeights += weights[j]; | |
} | |
const average = sum / sumOfWeights; | |
let sse = 0; | |
for (let k = 0; k < x.length; k++) { | |
sse += weights[k] * Math.pow(x[k][1] - func(x[k][0]), 2); | |
} | |
let sst = 0; | |
for (let l = 0; l < x.length; l++) { | |
sst += weights[l] * Math.pow(x[l][1] - average, 2); | |
} | |
return 1 - sse / sst; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment