Changing the Color of Cells With Small Sample Sizes

From Q
Jump to navigation Jump to search

Please refer to Modify Cell Content - Change Color of Cells with Small Sample Sizes for a more straightforward way of implementing the code on this page.

When the sample size of a column is less than 30, this script makes the cells in the column red and adds a footer explaining what it has done. It will also deal with situations where missing data causes the sample size of each column to vary by row.

This example can be run in C:\Program Files\Q\Examples\Cola.Q (this may be located on a different place on your computer depending upon how Q was installed). Create a table with Q2. Gender in the blue drop-down menu and Preferred cola in the brown drop-down menu.

var min_sample_size = 30; // What is the minimum sample size to use?
var color_to_use = "red"; // Which color do you want to use to highlight the cells?

// Figure out which cells need to be highlighted
var column_ns = table.get('Column n');// Get column sample sizes.
var colors = table.cellColors; // Obtain the current cell colors.
var color_flag = false; // Keep track of whether any cells have been highlighted.
var extra_footers = table.extraFooters;// Store the extra footnotes we generate for each blank column.
for (var column = 0; column < table.numberColumns; column++) {// loop through the columns
    for (var row = 0; row < table.numberRows; row++) {
	// Get the sample size for this cell
        var column_n = column_ns[row][column];
        // If the column's sample size is less than min_sample_size, make each cell in the column blank.
        if (column_n < min_sample_size) {
            colors[row][column] = color_to_use;
            color_flag = true;
        }
	}
}

// Apply changes to the table
if (color_flag = true) {
    table.cellColors = colors; // Set the new table colors
    extra_footers.push('Cells shown in ' + color_to_use + ' have a sample size that is smaller than ' + min_sample_size + '.');
    // Set the extra footnotes.
    table.extraFooters = extra_footers;
}

Note that:

  • This example will only work on tables that contain Column n.
  • To change the rule to reflect a sample size other than 30, replace 30 with your preferred minimum sample size.

See also