Regression - Diagnostic - Test Residual Heteroscedasticity extension

From Q
Jump to: navigation, search

Conduct a heteroscedasticity test on the residuals

Test for heteroscedasticity (non-constant variance) in the residuals of linear regression models. Also known as the Breusch-Pagan test. The null hypothesis of the test is homoscedasticity. You must select an output from Regression - Linear Regressionlinear regression to use this feature. See this blog post for an introduction to heteroscedasticity.


The following table shows the output from running this QScript on an output from Regression - Linear Regressionlinear regression.


Uses the ncvTest function from the car package.


Breusch, T. S. and Pagan, A. R. (1979) A simple test for heteroscedasticity and random coefficient variation. Econometrica 47, 1287--1294.

Bock, T. (2018, August 9). What is heteroscedasticity? [Blog post]. Retrieved from


includeWeb("QScript R Output Functions");

var is_displayr = (!!Q.isOnTheWeb && Q.isOnTheWeb());
if (!is_displayr)
    if (Q.fileFormatVersion() >= 17.13)
        alert("Please update Q to use this feature from the extension button, or run it from the menu via Create > Regression > Diagnostic > Heteroscedasticity.");

function main() {

    // The following 2 variables contain information specific to this diagnostic.
    var required_class = "Regression";
    var output_name_suffix = "heteroscedasticity";
    var item = checkSelectedItemClass(required_class);
    if (item == null)
        return false;
    var r_name = stringToRName(item.referenceName);

    // The following lines contain the R code to run
    var expression = "if (!identical(class(" + r_name + "$original), \"lm\"))\n    stop(\"" 
        + "Sorry, you must select an output from 'Regression - Linear Regression' to use this diagnostic.\")\n"
    expression += "flipFormat::SignificanceTest(\n    car::ncvTest(" + r_name
        + "),\n    'Test of Residual Heteroscedasticity (Breusch-Pagan)',\n    vars = NULL,\n = "
        + "deparse(substitute(" + r_name + ")),\n    reg.sample.description = " + r_name + "$sample.description)";

    return createROutput(item, expression, output_name_suffix);