Modify Whole Table or Plot - Show Each Statistic in Separate Column

From Q
Jump to navigation Jump to search


This rule re-arranges the numbers in the table so that statistics are shown in separate columns rather than above one another in each cell of the table. Significance highlighting from the original table will be shown in the cells for the first statistic. It is best to make any adjustments to the question in the brown drop-down from a separate table.

Example

This example applies the script to a crosstab between a question about Income and a banner that contains Age and Gender. The table is showing the Column % and n statistics.

Before:

StatisticsInSeparateColumnsBefore.PNG

After:

StatisticsInSeparateColumnsAfter.PNG

The two statistics are shown side-by-side.

Technical details

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

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();

form.setSummary("Show each statistic in a separate column");
form.setHeading("Show each Statistic in a Separate Column");
form.setInputControls([form.newLabel('Show statistics in adjacent columns rather than as rows in the table.')]);
 
if (Q.fileFormatVersion() <= 8.62 && table.blueQuestion.questionType == "Pick One - Multi" && belowTableExists())
    form.ruleNotApplicable("this rule is not currently compatible with this type of table. Please contact Q Support for a newer version");
 
// Store the initial state of the table
let initial_num_cols = table.numberColumns;
let initial_col_labels = table.columnLabels;
let initial_statistics = table.statistics;
 
// Determine the first non-text statistic to use to store the table data
// in the re-shaped table.
let table_stats_not_column_comparisons = initial_statistics.filter(function (stat) { return !isTextStatistic(stat); });
if (table_stats_not_column_comparisons.length == 0)
    form.ruleNotApplicable("there are only statistics related to the column comparisons on this table");
 
let target_stat = table_stats_not_column_comparisons[0];
let stats_on_final_table = [target_stat];
 
let num_stats = initial_statistics.length;
 
if (table.columnLabels != null && num_stats > 1) {
 
    let initial_col_spans = table.columnSpans;
    let initial_net_cols;
       if (Q.fileFormatVersion() >= 8.22)
           initial_net_cols = table.netColumns;
 
    // Determine the new locations of the original columns
    let original_columns_indices = [];
    for (let j = 0; j < initial_num_cols; j++)
        original_columns_indices.push(j);
    original_columns_indices = original_columns_indices.map(function(x) { return num_stats*x; });
 
    // Grab the stats and form new labels for the columns
    let initial_stat_values = initial_statistics.map(function (stat) { return table.get(stat); });
 
    // Set the table to display a single main statistic
    // (plus column-comparisons statistics if shown)
    table.statistics = stats_on_final_table;
 
    // Create new column labels
    let new_col_labels = [];
    for (let j = 0; j < initial_num_cols; j ++)
        new_col_labels = new_col_labels.concat(initial_statistics);
    new_col_labels = new_col_labels.map(function(s) {
        try {
            return table.getTranslation(s);
        } catch (e) {
            return s;
        }
    });

    // Expand the table
    let new_num_cols = new_col_labels.length;    
    for (let j = 0; j < initial_num_cols; j++) {
        let start_index = original_columns_indices[j];
        for (let k = 0; k < num_stats - 1; k++)
            table.insertColumnAfter(start_index, "");
    }
 
    // Expand the below_table if it's turned on
    if (belowTableExists()) {
        let is_1D = below_table.columnLabels == null;
        for (let j = 0; j < initial_num_cols; j++) {
            let start_index = original_columns_indices[j];
            for (let k = 0; k < num_stats - 1; k++) {
                if (is_1D)
                    below_table.insertRowAfter(start_index, "");
                else
                    below_table.insertColumnAfter(start_index, "");
            }
        }
    }
 
    // Build new statistics table from original statistics
    let new_stats = table.get(table.statistics[0]);
    let cell_text = table.cellText;
    for (let j = 0; j < initial_num_cols; j++) {
        for (let k = 0; k < num_stats; k++) {
            let cur_stats = initial_stat_values[k];
            if (!isTextStatistic(initial_statistics[k])) {
                for (let row = 0; row < table.numberRows; row++)
                    new_stats[row][j*num_stats + k] = cur_stats[row][j];
            } else {
                for (let row = 0; row < table.numberRows; row++) {
                    new_stats[row][j*num_stats + k] = NaN;
                    cell_text[row][j*num_stats + k] = [cur_stats[row][j]];
                }
            }
        }
    }
    table.columnLabels = new_col_labels;
    table.set(target_stat, new_stats);
    table.cellText = cell_text;
    table.clearColumnSpans();
 
    // Recombine the column labels as spans
    // First the column labels
    for (let j = 0; j < initial_col_labels.length; j++) {
        let start = j*num_stats;
        let end = start + num_stats;
        let index_array = [];
        for (let k = start; k < end; k++)
            index_array.push(k);
        table.spanColumns(index_array, initial_col_labels[j]);
    }
 
    // Now include all of the original spans
    for (let j = 0; j < initial_col_spans.length; j++) {
        let cur_inds = initial_col_spans[j].indices;
        let start = cur_inds[0]*num_stats;
        let end = cur_inds[cur_inds.length-1]*num_stats + num_stats;
        let index_array = [];
        for (let k = start; k < end; k++)
            index_array.push(k);
        table.spanColumns(index_array, initial_col_spans[j].label);
    }
    
     // Check if percentages option is turned on
    if (table.showPercentSign) {
        // Turn percentages off so we can specify which cells to show %
        table.showPercentSign = false 
        let cell_texts = table.cellText;
        let column_labels = table.columnLabels;

        // Loop through each cell and add percentages if % included in label
        for (let row = 0; row < table.numberRows; row++)
            for (let column = 0; column < table.numberColumns; column++)
                if (column_labels[column].indexOf("%")>-1) {
                    cell_texts[row][column] = ['%'];
                }
        table.cellText = cell_texts;
    } 

    let version = Q.fileFormatVersion();

    if (version >= 8.22) {
       // And keep track of the original NETs.
       let new_nets = [];
       initial_net_cols.forEach(function (col) {
           for (let j = 0; j < num_stats; j++)
               new_nets.push(num_stats*col + j);
       });
       table.netColumns = new_nets;
    }
 
    // Prevent hypothesis testing
    table.hypothesisTestingEnabled = false;
 
    table.showMissingAs('');
} else if (num_stats == 1)
    form.ruleNotApplicable('only a single statistic is selected in the table');
else
    form.ruleNotApplicable('statistics are already shown in separate columns on this table');

See also