Table Computations - Average of Each Row

From Q
Jump to navigation Jump to search


This rule adds an extra column to the right of the table which shows the average of the statistics that are shown in the rows. Columns which are duplicates of other columns, for example, and 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

AverageOfColumnsRule.PNG

Technical details

Statistical tests are not performed on these cells.

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('JavaScript Array Functions');
includeWeb('Table JavaScript Utility Functions');

excludeRTables();
table.requireNumericTable();

// Set up controls for user input.
form.setHeading('Average of Each Row');
form.setSummary('Average of each row');
// Get the list of statistics on the table.
let label_statistic = form.newLabel('Statistic to use:');
let valid_statistics = table.statistics.filter(function (statistic) {
    return !isTextStatistic(statistic);
});

let valid_stats_translated = valid_statistics.map(function(s) {
    try {
        return table.getTranslation(s);
    } catch(e) {
        return s;
    }
});

if (valid_statistics.length == 0)
    form.ruleNotApplicable('there are no numeric statistics in this table');
if (table.numberColumns == 1)
    form.ruleNotApplicable('the columns of this table represent statistics and cannot be averaged');
if (table.availableStatistics.indexOf('Not Duplicate') == -1)
    form.ruleNotApplicable('the data in this table is not appropriate');

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 col_position = form.newComboBox('colPos', ['Left', 'Right']);
col_position.setDefault('Right');
let position_label = form.newLabel('Position: ');
form.setInputControls([desc, label_statistic, combo_box, position_label, col_position]);

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

// What is the last column in this span?
let new_col_position = col_position.getValue();
let last_col = new_col_position === 'Right' ? table.numberColumns - 1 : null;
// Add a new Average column.
table.insertColumnAfter(last_col, 'Row 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_cols = getNotDuplicateCols();
let start_pos = new_col_position === 'Right' ? 0 : 1;
let end_pos = table.numberColumns - (new_col_position === 'Right');

// Remember the index of the new Average column.
let new_col_index = new_col_position === 'Right' ? table.numberColumns - 1 : 0;
// For each row, sum its statistics.
for (let row = 0; row < table.numberRows; row++) {
    // For the specified statistic in the table...
    let sum = 0;
    let unique_cols = 0;
    let average = NaN;
    for (let col = start_pos; col < end_pos + 1; col++) {
        // If this cell is not a duplicate...
        if (!isNaN(not_duplicates[row][col]) &&
            (not_duplicate_cols[col] == 1 || pick_one_multi_vars_across_rows) &&
            !isNaN(values[row][col])) {
            // Add its average value to this rows' sum.
            sum +=  values[row][col];
            // And increase the count of non-duplicate columns.
            unique_cols++;
        }
        // Compute the average.
        if (unique_cols > 0)
            average = sum / unique_cols;
    }
    // Store the average in the new Average column we added above.
    values[row][new_col_index] = average;
    // Store the values of the Average column into the table.
    table.set(statistic, values);
}

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

See also