Table Computations - Average of Each Column

From Q
Jump to navigation Jump to search


This rule adds an extra row to the bottom of the table which shows the average of the statistics that are shown in the columns. Rows which are duplicates of other rows, for example the NET row, are not included in the computation of the average. If there is more than one statistic in the table, the user may select the statistic to use.

Example

AverageOfRowsRule.PNG

Technical details

Statistical tests are not performed on these cells. Averaging is not performed on the statistics shown in Statistics - Right.

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

includeWeb('Table JavaScript Utility Functions');

excludeRTables();
table.requireNumericTable();

// Set up controls for user input.
form.setSummary('Average of each column');

// Set up controls for user input.
form.setHeading('Average of Each Column');
let label_statistic = form.newLabel('Statistic to use:');
let valid_statistics = table.statistics.filter(function (statistic) {
    return !isTextStatistic(statistic);
});
if (valid_statistics.length == 0)
    form.ruleNotApplicable('there are no numeric statistics in this table');
if (table.numberRows == 1)
    form.ruleNotApplicable('there is a single row on this table');
if (table.availableStatistics.indexOf('Not Duplicate') == -1)
    form.ruleNotApplicable('the data in this table is not appopriate');

let valid_stats_translated = valid_statistics.map(function(s) {
    try {
	return table.getTranslation(s);
    }catch(e) {
	return s;
    }
});
let desc = form.newLabel('Adds an extra row to the table showing the average of the chosen column statistic accross all rows');
desc.lineBreakAfter = true;
let combo_box = form.newComboBox('statistic', valid_stats_translated);
combo_box.setDefault(valid_stats_translated[0]);
combo_box.lineBreakAfter = true;
let row_position = form.newComboBox('rowPos', ['Top', 'Bottom']);
row_position.setDefault('Bottom');
let position_label = form.newLabel('Position: ');
form.setInputControls([desc, label_statistic, combo_box, position_label, row_position]);

let statistic_translated = combo_box.getValue();
let statistic = valid_statistics[valid_stats_translated.indexOf(statistic_translated)];

// Insert a new row to store the numbers.
let new_row_position = row_position.getValue();
let last_row = new_row_position === 'Bottom' ? table.numberRows - 1 : null;

insertRowAfterComplete(last_row, 'Column Average')

// Get the values for statistic
let values = table.get(statistic);

// Get the not duplicate markers for each cell.  This
// indicates whether the cell has been copied from
// another cell, such as when NETs are created.
let not_duplicates = table.get('Not Duplicate');
let pick_one_multi_vars_across_rows = table.blueQuestion.questionType == 'Pick One - Multi' &&
                                      table.blueQuestion.dataReduction.transposed;
let not_duplicate_rows = getNotDuplicateRows();

let new_row_index = new_row_position === 'Bottom' ? table.numberRows - 1 : 0;
let start_pos = new_row_position === 'Bottom' ? 0 : 1;
let end_pos = table.numberRows - (new_row_position === 'Bottom');

// For each column...
for (let column = 0; column < table.numberColumns; column++) {
    // Keep track of the sum of averages, and the number of
    // non-duplicate rows so far.
    let sum = 0;
    let unique_rows = 0;

    // For each row...
    for (let row = start_pos; row < end_pos; row++)
        // If this cell is not a duplicate...
        if (!isNaN(not_duplicates[row][column]) && (not_duplicate_rows[row] == 1 || pick_one_multi_vars_across_rows) && !isNaN(values[row][column])) {
            // Add its average value to this column's sum.
            sum +=  values[row][column];
            // And increase the count of non-duplicate rows.
            unique_rows++;
        }

    // We now have a sum of all the averages in this column.
    // Compute the average.
    let average = NaN;
    if (unique_rows > 0)
        average = sum / unique_rows;

    // Store the average in the new 'Column Average' row
    // we added above.
    values[new_row_index][column] = average;
}


function getNotDuplicateRows() {
    let not_duplicate = table.get('Not Duplicate');
    let results = [];
    for (let i = 0; i < table.numberRows; i++)
        for (let j = 0; j < table.numberColumns; j++) {
            if (not_duplicate[i][j] == 1) {
                results.push(1);
                break;
            }
            if (j == table.numberColumns - 1)
                results.push(0); // only run if all cells in the row are duplicate
        }
    return results;
}

// Use our new average values.
table.set(statistic, values);

// 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;
}

See also