Multivariate - All Combinations Of Pick Any Categories

From Q
Jump to: navigation, search

This QScript computes the proportion of respondents to select each possible combination of the categories of a Pick Any question.

Example

Combinations.png

Technical details

  • This QScript creates a new variable that shows all of the combinations of options that appear in a set of multiple response variables (that is, variables from a Pick Any question). You can select the variables that you want to use from a list of appropriate variables.
  • The categories shown in the output table are created to be mutually exclusive. In the example above, the row 8: Coke & Diet Coke shows respondents that selected both Coke and Diet Coke and no other options.
  • Each combination shown in the table is associated with a number, and these are sorted in ascending order. The absence of a number indicates that the combination of options that is associated with that number has not been selected by any respondent.
  • The new question will not be updated if the underlying variables are changed. If you make changes to the variables that you used, delete this question and run the QScript again. Importantly, this includes the case when you update your Q project with new data.

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

// Multivariate - All Combinations Of Pick Any Categories
// Uses https://msdn.microsoft.com/en-us/library/aa289166.aspx
 
includeWeb('QScript Selection Functions');
 
if (!main())
    log('QScript was cancelled.');
 
function main() {
    // Input variables
    var data_file = requestOneDataFileFromProject();    
    var pick_any_questions = data_file.questions.filter(isQuestionPickAnyOrPickAnyGrid).filter(isQuestionNotHidden).filter(isQuestionValid).filter(function (q) { return !q.isBanner; });
    if (pick_any_questions.length == 0) {
        alert('There are no Pick Any or Pick Any - Grid questions in this project (these are required for this analysis).');
        return false;
    }
 
    var pick_any_variables = getVariablesFromQuestions(pick_any_questions);
    var selected_variables;
 
    do {
        selected_variables = selectManyVariablesByQuestionNameAndLabel('Select the alternatives (variables) to be included in the analysis.  Only variables from Pick Any and Pick Any - Grid questions can be selected:',
                                                                       pick_any_variables).variables;
    } while (!checkTwoOrMoreVariables(selected_variables))
 
    // Getting the variable labels 
    var number_of_alternatives = selected_variables.length;
    var alternative_labels = new Array(number_of_alternatives);
    for (var i = 0; i < number_of_alternatives; i++)
        alternative_labels[i] = selected_variables[i].label.replace(/\'/g, "\\'").replace(/\"/g, '\\"');
    // Check that alternative labels are different from each other
    if (!checkLabelsNotDuplicate(alternative_labels))
        return false;
 
    // Creating the variable.
    var expr = "function choose(_n, _k) {\n";
    expr += "    if (_n < _k)\n";
    expr += "        return 0;\n";
    expr += "    var _result = 1;\n";
    expr += "    for (var _j = 0; _j < _k; _j++)\n";
    expr += "        _result *= (_n - _j) / (_j + 1);\n";
    expr += "     _result = Math.round(_result);\n";
    expr += "    return _result;\n";
    expr += "}\n";
    expr += "\n";
    expr += "var _labels = ['" + alternative_labels[0] + "'";
    var var_label = "Combinations of " + alternative_labels[0];
    for (var i = 1; i < number_of_alternatives; i++){ 
        expr += ", '" + alternative_labels[i] +  "'";
        var_label += ", " + alternative_labels[i];
    }
    expr += "];\n";
    expr += "var _names = [" + selected_variables[0].name;
    for (var i = 1; i < number_of_alternatives; i++)
        expr += ", " + selected_variables[i].name;
    expr += "];\n";
    expr += "var _nvar = _names.length;\n";
    expr += "var _result = '';\n";
    expr += "var _comb = [];\n";
    expr += "for (var _i = 0; _i < _nvar; _i++) {\n";
    expr += "    if(_names[_i]) {\n";
    expr += "        _result += _result == '' ? _labels[_i] : ' & ' + _labels[_i];\n";
    expr += "        _comb.push(_i);\n";
    expr += "    }\n";
    expr += "}\n";
    expr += "_index = 0;\n";
    expr += "for (var _i = 1; _i <= _comb.length; _i++) {\n";
    expr += "    _index += choose(_nvar, _i);\n";
    expr += "    _index -= choose(_nvar - 1 - _comb[_i - 1], _comb.length - _i + 1);\n";
    expr += "}\n"
    expr += "_comb.length == 0 ? '0: NOTHING' : _index + ': ' + _result;";
 
    if (var_label.length > 200)
        var_label = var_label.substring(0,200);
    var v = data_file.newJavaScriptVariable(expr, true, preventDuplicateVariableName(data_file, "combinationsText"), var_label + " TEXT", null);
    v.question.isHidden = true;
    var vv = v.duplicateAs("Categorical");
    vv.question.name = preventDuplicateQuestionName(data_file, var_label); 
 
    // creating the table
    var table = project.report.appendTable();
    table.primary = vv.question;
    log('A table called ' + table.name + ' has been added to the project.');
    return true;
}
 
function isQuestionPickAnyOrPickAnyGrid(question) {
    var q_type = question.questionType;
    return q_type == 'Pick Any' || q_type == 'Pick Any - Grid';
}
 
 
function checkTwoOrMoreVariables(variables) {
    if (variables.length >= 2)
        return true;
    alert('There needs to be two or more variables.\n\nClick OK to reselect variables or Cancel to stop the script.');
    return false;
}
 
function checkLabelsNotDuplicate(labels) {
    if (labels.length <= 1)
        return true;
    for (var i = 1; i < labels.length; i++) {
        for (var j = 0; j < i; j++) {
            if (labels[i] == labels[j]) {
                alert('The selected alternatives have labels that are identical or too similar to each other. Change the labels or select different alternatives.');
                return false;
            }
        }
    }
    return true;
}


See also