Tables - Banner Tables

From Q
Jump to: navigation, search
Related Videos
Part 4 of Creating Tables in Q (Video)
 

This QScript generates banner tables for a list of specified questions. This is an alternative to creating a Banner and then using Basic Tables to generate crosstabs with the banner, and automatically flattens any two-dimensional (grid) questions.

Example

BannerExample.png

Technical details

You will be asked to specify:

  1. The questions to place in the rows of the tables.
  2. The questions to use in the banner.

Any Pick One - Multi, Pick Any - Grid and Number - Grid questions will be copied and flattened before using them in a crosstab. The flattened copy will contain all of the cells from the original question in a single column or row.

How to apply this QScript

  • Start typing the name of the QScript into the Search features and data box in the top right of the Q window.
  • Click on the QScript when it appears in the QScripts and Rules section of the search results.

OR

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

Customizing the QScript

This QScript is written in JavaScript and can be customized by copying and modifying the JavaScript.

Customizing QScripts in Q4.11 and more recent versions

  • Start typing the name of the QScript into the Search features and data box in the top right of the Q window.
  • Hover your mouse over the QScript when it appears in the QScripts and Rules section of the search results.
  • Press Edit a Copy (bottom-left corner of the preview).
  • Modify the JavaScript (see QScripts for more detail on this).
  • Either:
    • Run the QScript, by pressing the blue triangle button.
    • Save the QScript and run it at a later time, using Automate > Run QScript (Macro) from File.

Customizing QScripts in older versions

  • Copy the JavaScript shown on this page.
  • Create a new text file, giving it a file extension of .QScript. See here for more information about how to do this.
  • Modify the JavaScript (see QScripts for more detail on this).
  • Run the file using Automate > Run QScript (Macro) from File.

JavaScript

includeWeb('QScript Selection Functions');
includeWeb('QScript Table Functions');
includeWeb("QScript Functions to Generate Outputs");


if (!main())
    log("QScript cancelled.");
else 
    conditionallyEmptyLog("QScript finished.");

function main() {
var column_q_choices = [];
    var row_q_choices = [];
    var is_cancelled = false;
     
    if(!requireDataFile())
        return false;
     
    if (project.dataFiles.length > 1) {
        try {
            var data_file = selectOneDataFile('There is more than one data file in your project. ' + 
                'Please select the data file to use:', project.dataFiles)
        } catch(e) {
            return false;
        }
    } else {
        var data_file = project.dataFiles[0];   
    }
     
     
    var candidate_questions = data_file.questions;
    candidate_questions = candidate_questions.filter(function (q) { return !q.isHidden && q.questionType.indexOf("Text") == -1 && q.isValid; });
    // Exclude any questions where all the categories are set to missing
    candidate_questions = candidate_questions.filter(function (q) { 
                                                        if (q.questionType.indexOf("Pick One") == 0) {
                                                            var uniques = q.uniqueValues;
                                                            var value_attributes = q.valueAttributes;
                                                            var non_missings = uniques.filter(function (x) { return !value_attributes.getIsMissingData(x); });
                                                            return non_missings.length > 0;
                                                        } else
                                                            return true;
                                                    });
 
    candidate_questions.forEach(function (q) {
        row_q_choices.push(q);
        if (["Pick One", "Pick One - Multi", "Pick Any", "Pick Any - Grid", "Pick Any - Compact"].indexOf(q.questionType) > -1 && !q.isBanner)
            column_q_choices.push(q);
    });
 
    if (row_q_choices.length == 0 || column_q_choices.length == 0) {
        log("There are no appropriate questions to use for banner tables.");
        return false;
    }

    var row_questions, column_questions;
    while (!row_questions || !oneOrMoreQuestions(row_questions))
        row_questions = selectManyQuestions('Please select questions to place in the rows:', row_q_choices).questions;
 
    while (!column_questions || !oneOrMoreQuestions(column_questions))
        column_questions = selectManyQuestions('Please select questions to place in the banner:', column_q_choices).questions;
     

    flattenSelectedQuestions(column_questions);
    flattenSelectedQuestions(row_questions);
 
    // place each question inside an array
    for (var i = 0; i < column_questions.length; i++)
        column_questions[i] = [column_questions[i]];
 
    // create banner from column questions
    var banner_name = preventDuplicateQuestionName(data_file, 'BANNER');
 
    var banner_q;
    if (fileFormatVersion() >= 8.58) {
        banner_q = data_file.createBanner(banner_name, column_questions, false, true);
    } else {
        banner_q = data_file.createBanner(banner_name, column_questions);
 
        // remove NET from each span
        for (var i = 0; i < banner_q.variables.length; i++) {
            var variable = banner_q.variables[i];
            for (var j = 0; j < column_questions.length; j++)
                if (variable.label == column_questions[j][0].name + ': NET') {
                    variable.deleteVariable();
                    break;
                }
        }
    }
 
    // check for large crosstabs
    var q_pairs_large = [];
    for (var i = 0; i < row_questions.length; i++) {
        var row_q = row_questions[i];
        if (questionsYieldLargeCrosstab(row_q, banner_q))
            q_pairs_large.push('"' + row_q.name + ' and ' + banner_q.name + '"');
    }
 
    // warn about large crosstabs
    if (q_pairs_large.length == 1) {
        is_cancelled = !confirm('The question pair ' + q_pairs_large[0] +
            ' will result in a very large table.\n\n' +
            'Very large tables are not likely to be interesting, will be slow to calculate ' +
            'and will generate a warning message when viewed.\n\n' +
            'Do you wish to continue?');
    } else if (q_pairs_large.length > 1) {
        var q_pairs_large_examples = '';
        for (var i = 0; i < Math.min(3, q_pairs_large.length); i++)
            q_pairs_large_examples = q_pairs_large_examples + q_pairs_large[i] + '\n';
        is_cancelled = !confirm('There are ' + q_pairs_large.length + ' very large tables that will be created.\n\n' +
            'Very large tables are not likely to be interesting, will be slow to calculate ' +
            'and will generate a warning message when viewed.\n\n ' +
            'Question pairs that will result in very large tables include:\n' + q_pairs_large_examples + '\n' +
            'Do you wish to continue?');
    }
    
     
    if (is_cancelled) {
        log('QScript cancelled.');
        return false;
    } else {
        var banner_tables = project.report.appendGroup();
        banner_tables.name = 'Banner Tables';
     
        for (var i = 0; i < row_questions.length; i++) {
            var table = banner_tables.appendTable();
            table.primary = row_questions[i];
            table.secondary = banner_q;
            if (!addStat(table, 'Row %') * !addStat(table, 'n')) // non short-circuiting &&
                !addStat(table, 'Column n');
        }
        if (fileFormatVersion() > 8.65)
            project.report.setSelectedRaw([banner_tables.subItems[0]]);
        conditionallyEmptyLog('Banner tables have been added to the "' + banner_tables.name + '" group.');
        return true;
    }

}
 
    
 
function flattenSelectedQuestions(selectedQuestions) {
    for (var i = 0; i < selectedQuestions.length; i++) {
        var q = selectedQuestions[i];
        var flattened_name = q.name + ' (flattened)';
        var q_flattened = data_file.getQuestionByName(flattened_name);
        if (q_flattened == null) {
            if (q.questionType == 'Pick One - Multi') {
                q_flattened = pickOneMultiToPickAnyFlattenByRows(q);
            } else if (q.questionType == 'Pick Any - Grid') {
                q_flattened = q.duplicate(flattened_name);
                q_flattened.questionType = 'Pick Any';
            } else if (q.questionType == 'Number - Grid') {
                q_flattened = q.duplicate(flattened_name);
                q_flattened.questionType = 'Number - Multi';
            }
        }
        if (q_flattened != null)
            selectedQuestions.splice(i, 1, q_flattened);
    }
}
 
function addStat(table, stat) {
    cell_stats = table.cellStatistics;
    cell_stats.push(stat);
    table.cellStatistics = cell_stats;
    return table.cellStatistics.indexOf(stat) > -1;
}
 
function oneOrMoreQuestions(questions) {
    if (questions.length == 0) {
        alert('Select one or more questions.');
        return false;
    }
    return true;
}


See also