Create New Variables - Combine Several Questions as a Grid

From Q
Jump to: navigation, search

This QScript combines several Pick Any questions into a Pick Any - Grid question, or several Number - Multi questions into a Number - Grid. This can be used to combine data from aided/unaided awareness questions, or when questions from a grid have been stored in the data file without appropriate labelling.

When the script runs you will be asked to select the questions to combine and a name for the new question. The questions that you select should all have the same set of variable labels in the same order. A new question will be created and shown in your report.

Example

In this example two Awareness questions are combined into a grid. Note that the two input questions have identical labels.

CombinePickAny.PNG

Technical details

When you create a Pick Any - Grid or Number - Grid question, Q uses the variable labels to determine the correct layout of the grid. In some cases the information about row labels and column labels is not stored in the file. This QScript derives appropriate labels by adding the name of each question to the existing variable labels. It is usually better to ask your data provider to set up the labels in your file so that Q can read the grid structure automatically when you import the data, and the recommended specifications are linked here.

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 Utility Functions");
includeWeb("QScript Functions to Generate Outputs");


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

function main() {

    var web_mode = (!!Q.isOnTheWeb && Q.isOnTheWeb());
    var allowed_types = ["Numeric - Multi", "Binary - Multi"];
    var selected_questions = selectInputQuestions(allowed_types);
    if (!selected_questions)
        return false;
    if (!areQuestionsValidAndNonEmpty(selected_questions))
        return false;
    if (selected_questions.length < 2) {
    	log("You must select at least 2 appropriate questions.");
    	return false;
    }
    var data_file = getDataFileFromQuestions(selected_questions);
    if (!data_file)
        return false;


    // Make sure all are numeric or all are pick any
    var prop_name = web_mode ? "variableSetStructure" : "questionType"
    if (!selected_questions.map(function (q) { return q[prop_name]; }).every(function (type) { return type == selected_questions[0][prop_name]; })) {
    	log("Questions are of different types and cannot be combined.");
    	return false;
    }

    var is_categorical = web_mode ? selected_questions[0].variableSetStructure == "Binary - Multi" : selected_questions[0].questionType == "Pick Any";

    // Check labels
    var all_labels = selected_questions.map(function (q) { return q.variables.map(function (v) { return v.label; }); });
    
    // Check lengths
    if (!all_labels.every(function (label_array) { return label_array.length == all_labels[0].length; })) {
    	log("The selected questions have different numbers of variables and cannot be combined.");
    	return false;
    }
    // Check all sets equal
    function labelArraysEqual(array_1, array_2) {
    	var are_equal = true;
    	array_1.forEach(function (label, ind) {
    		if (label != array_2[ind])
    			are_equal = false;
    	});
    	return are_equal;
    }
    if (!all_labels.every(function (label_array) { return labelArraysEqual(label_array, all_labels[0]); }) ) {
    	log("The labels from these questions do not match, and so the questions cannot be combined.");
    	return false;
    }

    // Copy variables and edit labels
    var new_vars = [];
    var last_var = null;
    selected_questions.forEach(function (q) {
        
        try {
            q.variables.forEach(function (v) {
                var new_var = v.duplicate();
                new_vars.push(new_var);
                new_var.label = q.name + " - " + v.label;
            });
        } catch (e) {
             q.variables.forEach(function (v) {
                var q_below = data_file.getVariableByName(v.name);
                var new_linked = preventDuplicateVariableName(data_file, v.name) 
                var new_var = data_file.newJavaScriptVariable(v.name, false, new_linked, v.name, q_below);
                new_vars.push(new_var);
                new_var.label = q.name + " - " + v.label;
            });
        }    
            
    });
    
    // Set question and create summary tables
    var new_name = selected_questions.map(function(q){ return q.name }).join(' + ');    
    if (!web_mode)
        new_name = prompt("Enter a name for the new grid question:", new_name);
    new_name = preventDuplicateQuestionName(data_file, new_name);
    var new_q = data_file.setQuestion(new_name, (is_categorical ? "Pick Any - Grid" : "Number - Grid"), new_vars);

    if (!web_mode)
    {
        var new_group = project.report.appendGroup();
        new_group.name = new_name;
        var new_table = new_group.appendTable();
        new_table.primary = new_q;

        if (fileFormatVersion() > 8.65)
            project.report.setSelectedRaw([new_table]);
        else
            conditionallyEmptyLog("A table showing the new question has been added into the folder " + new_name);
    }
    return true;
}

Prior to the 15th of December, 2015, this page was known as Data Manipulation - Combine Several Questions as a Grid

See also