Weight - Apply Weight to Column Span

From Q
Jump to navigation Jump to search


This rule applies a weight to all the columns within a column span of a table. This is achieved by generating a new copy of the table with the weight applied and copying the statistics into the main table.

Technical details

The significance testing results for the weighted columns are taken from the weighted table and no attempt is made to reconcile tests between the weighted and unweighted portions of the table.

How to apply this rule

For the first time in a project

  • Select the table(s)/chart(s) that you wish to apply the rule to.
  • Start typing the name of the Rule into the Search features and data box in the top right of the Q window.
  • Click on the Rule when it appears in the QScripts and Rules section of the search results.

OR

  • Select Automate > Browse Online Library.
  • Choose this rule from the list.

Additional applications of the rule

  • Select a table or chart that has the rule and any table(s)/chart(s) that you wish to apply the rule to.
  • Click on the Rules tab (bottom-left of the table/chart).
  • Select the rule that you wish to apply.
  • Click on the Apply drop-down and choose your desired option.
  • Check New items to have it automatically applied to new items that you create. Use Edit > Project Options > Save as Template to create a new project template that automatically uses this rule.

Removing the rule

  • Select the table(s)/chart(s) that you wish to remove the rule from.
  • Press the Rules tab (bottom-right corner).
  • Press Apply next to the rule you wish to remove and choose the appropriate option.

How to modify the rule

  • Click on the Rules tab (bottom-left of the table/chart).
  • Select the rule that you wish to modify.
  • Click Edit Rule and make the desired changes. Alternatively, you can use the JavaScript below to make your own rule (see Customizing Rules).

JavaScript

You can find a simpler version of this code, which does not contain the controls, here.

table.requireNumericTable();
table.requireOriginalRowsColumns();
includeWeb('Table JavaScript Utility Functions');
includeWeb('JavaScript Array Functions');
includeWeb('QScript Utility Functions');

excludeRTables();

if (!table.columnLabels)
    form.ruleNotApplicable('the table only has a single column');

let spans = table.columnSpans;
let span_labels = spans.map(function(s) { return s.label });
if (arrayHasDuplicateElements(span_labels));
    span_labels = enumerateDuplicatesInStringArray(span_labels, '(', ')');

if (span_labels.length < 1)
    form.ruleNotApplicable('no column spans exist for this table');

if (!table.blueQuestion.dataFile.equals(table.brownQuestion.dataFile))
    form.ruleNotApplicable(correctTerminology('table has questions from different data files'));
let variables = table.blueQuestion.dataFile.variables;

let weight_variables = variables.filter(function(v) { return v.question.isWeight; });
let weight_names = weight_variables.map(function(v) { return v.name; });
let weight_labels = weight_variables.map(function(v) { return v.question.name; });

if (weight_variables.length < 1)
    form.ruleNotApplicable('no weight variables have been found');

// Set up controls for user input.
form.setHeading('Apply Weight to Column Span');
let label_column = form.newLabel('Column span to weight:');
let combobox_column = form.newComboBox('column', span_labels);
combobox_column.setDefault(span_labels[0]);
let label_weight = form.newLabel('Weight:');
let combobox_weight = form.newComboBox('weight', weight_labels);
combobox_weight.lineBreakAfter = true;
let description = form.newLabel('This rule applies a weight to all the columns within a specified column span of a table.');
description.lineBreakAfter = true;
form.setInputControls([description, label_column, combobox_column, label_weight, combobox_weight]);

// Prevent Statistics - Right and Statistics - Below
if (belowTableExists())
    if (fileFormatVersion() <= 8.41 && below_table.statistics.length > 0)
        table.suppressOutput('This table cannot be displayed because Statistics - Below have been selected for this ' +
                             'table, and this is not compatible with this Rule.  Either remove the Statistics - ' +
                             'Below selection (right-click on the table) or remove the Rule.');
if (rightTableExists())
    if (right_table.statistics.length > 0)
        table.suppressOutput('This table cannot be displayed because Statistics - Right have been selected for this ' +
                             'table, and this is not compatible with this Rule.  Either remove the Statistics - ' +
                             'Right selection (right-click on the table) or remove the Rule.');

let span = combobox_column.requireValue();
let selected_weight_label = combobox_weight.requireValue();
let weight = weight_names[weight_labels.indexOf(selected_weight_label)];

// Obtain the column indices for the selected span
let spandex = span_labels.indexOf(span);
let columns = spans[spandex].indices;

let rule_name = 'Weight column span: "' + span + '" by "' + selected_weight_label + '"';
form.setSummary(rule_name);
let weighted_table = calculateTable(table.blue, table.brown, ['!UseQFilters'], weight);

// Copy the weighted statistics for the column to the current table
let stats = table.statistics;
prepareAllTableStats(table);
for (let i = 0; i < columns.length; i++) {
    let column = columns[i];
    for (let stat = 0; stat < stats.length; stat++) {
        let weighted_values = weighted_table.get(stats[stat]);
        let main_values = table.get(stats[stat]);
        for (let row = 0; row < table.numberRows; row++)
            main_values[row][column] = weighted_values[row][column];
        // Set the altered values to the main table.
        table.set(stats[stat], main_values);
    }
}

// Copy the Significance Testing from the weighted table
let cell_arrows = table.cellArrows;
let cell_font_colors = table.cellFontColors;
let cell_significance = table.cellSignificance;
let weight_cell_arrows = weighted_table.cellArrows;
let weight_cell_font_colors = weighted_table.cellFontColors;
let weight_cell_significance = weighted_table.cellSignificance;
for (let i = 0; i < columns.length; i++) {
    let column = columns[i];
    for (let row = 0; row < table.numberRows; row++) {
        cell_arrows[row][column] = weight_cell_arrows[row][column];
        cell_font_colors[row][column] = weight_cell_font_colors[row][column];
        cell_significance[row][column] = weight_cell_significance[row][column];
    }
}
table.cellArrows = cell_arrows;
table.cellFontColors = cell_font_colors;
table.cellSignificance = cell_significance;


// In newer versions of Q, also copy Statistics - Below
if (fileFormatVersion() > 8.41 && belowTableExists()) {
    let weighted_marginal_table = Q.calculateTable(table.blue, table.brown, ['!UseQFilters'], weight, 'Below');

    // Prepare marginal statistics so that they are all available
    prepareAllTableStats(below_table);

    // Significance testing for statistics - below
    // Copy the Significance Testing from the weighted table
    let weight_cell_arrows = weighted_marginal_table.cellArrows;
    let weight_cell_font_colors = weighted_marginal_table.cellFontColors;
    let weight_cell_significance = weighted_marginal_table.cellSignificance;
    
    let cell_arrows = below_table.cellArrows;
    let cell_font_colors = below_table.cellFontColors;
    let cell_significance = below_table.cellSignificance;

    for (let i = 0; i < columns.length; i++) { //looping through the columns in the selected span
        let column_index = columns[i];
        weighted_marginal_table.availableStatistics.forEach(function (stat) {
            let temp_stats = weighted_marginal_table.get(stat);
            let current_stats = below_table.get(stat);
            // Copy stats depending on the orientation of the table that has been returned by table.get
            if (temp_stats.length == 1) {
                current_stats[0][column_index] = temp_stats[0][column_index];
            } else {
                current_stats[column_index][0] = temp_stats[column_index][0];
            }
            below_table.set(stat, current_stats);
        });

        if (cell_arrows.length == 1) {
            cell_arrows[0][column_index] = weight_cell_arrows[0][column_index];
            cell_font_colors[0][column_index] = weight_cell_font_colors[0][column_index];
            cell_significance[0][column_index] = weight_cell_significance[0][column_index];
        } else {
            cell_arrows[column_index][0] = weight_cell_arrows[column_index][0];
            cell_font_colors[column_index][0] = weight_cell_font_colors[column_index][0];
            cell_significance[column_index][0] = weight_cell_significance[column_index][0];
        }
    }

    below_table.cellArrows = cell_arrows;
    below_table.cellFontColors = cell_font_colors;
    below_table.cellSignificance = cell_significance;

}


let footers = table.extraFooters;
footers.push(span + ' weighted by ' + selected_weight_label);
table.extraFooters = footers;

// Returns true if Statistics - Right are available for this table.
// This function needs to be kept in the main body of the rule to ensure
// that right_table is included properly before the rule code is
// executed.
function rightTableExists() {
    let exists = true;
    try {
        right_table.statistics;
    } catch (e) {
        exists = false;
    }
    return exists;
}

// Force Q to calculate all of the available statistics in the table before continuing
function prepareAllTableStats(table) {
    if (table.availableStatistics.indexOf('Minimum') >= 0)
        table.get('Minimum');
}

See also