Filtering Rows in a Grid

From Q
Jump to navigation Jump to search

Alters the table's results (i.e., 'statistics') so that each row (soft drink brand) is showing statistics filtered to respondents that prefer the brand.

It does this by finding filters that have the same name as the brand name shown in the rows of the table.

This example can be run using the question Brand Associations in C:\Program Files\Q\Examples\Cola.Q (this file may be in a different place on your computer).

The explanation for how this example works is contained in comments within the code snippet below. However, a few additional things to note:

This script will cause significance results to be displayed incorrectly. Please read Caveats for Table JavaScript before using this script.

var brands_to_filter = {
    'Coke': 'CokePreferred',
    'Diet Coke': 'DietCokePreferred',
    'Coke Zero': 'CokeZeroPreferred',
    'Pepsi': 'PepsiPreferred',
    'Diet Pepsi': 'PepsiLightPreferred',
    'Pepsi Max': 'PepsiMaxPreferred',
    'None of these': 'Indifferent'
};

var brands = table.rowLabels;// The row labels (brand names).
for (var row = 0; row < table.numberRows; row++) {// For each row (brand)...
    var filters = ['!UseQFilters'];//get any existing filters for the table
    var brand_filter = brands_to_filter[brands[row]];// Find the name of the filter with the same label as the row
    if (brand_filter) //add the brand filter to the list of filters
        filters.push(brand_filter);
    var brand_table = calculateTable(table.blue, table.brown, filters, '!UseQWeight');// Run the table.
    // Copy the statistics for this row (brand) from the filtered table to the main table
    var stats = table.statistics;
    for (var stat = 0; stat < stats.length; stat++) {//looping through all the statistics on the table
        var filtered_values = brand_table.get(stats[stat]);// Get the values from the filtered table.
        var main_values = table.get(stats[stat]);// Get the values from the main table.
        // Copy the values from the filtered table to the main table for this row/brand
        for (var column = 0; column < table.numberColumns; column++)
            main_values[row][column] = filtered_values[row][column];
        table.set(stats[stat], main_values);// Set the altered values to the main table.
    }
}

See also