Add Empty Categories to a Question
Jump to navigation
Jump to search
Sometimes you may have an option in a questionnaire which none of the respondents select, and if you are using an Excel-style file the category will not appear when you create a table for the question. You may wish to have a table which includes the missing category, and which shows 0%.
The example below shows how you can use QScript to add in an empty category to a question. You can use this example on Cola.Q, from Q's examples. To do so,
- Select File > Open > Example Project.
- Open Cola.Q
- Select Automate > Open QScript (Macro) Editor.
- Copy and paste the code into the editor.
- Click the play icon (triangle) in the top toolbar.
In this example:
- A new copy of the Gender question is created using a JavaScript variable.
- The original labels are copied into the new question.
- A new category is added to the new question by setting a label (Prefer not to answer) for a value which does not exist (3).
includeWeb("QScript Utility Functions");
includeWeb("QScript Value Attributes Functions");
var data_file = project.dataFiles[0];
var question = data_file.getQuestionByName("Q2. Gender");
var variable = question.variables[0];
// Create new copy of variable using JavaScript
var new_variable = data_file.newJavaScriptVariable(variable.name, false, preventDuplicateVariableName(data_file, variable.name), variable.label + " - Complete");
new_variable.question.questionType = "Pick One";
data_file.moveAfter([new_variable], variable);
// Copy existing values labels into new variable
copyValueAttributesForVariable(variable, new_variable);
// Add a new category by setting a label for a value that does not exist yet.
var value_attributes = new_variable.valueAttributes;
value_attributes.setLabel(3, "Prefer not to answer");
// Show the results
var new_table = project.report.appendTable();
new_table.primary = new_variable.question;
project.setSelectedRaw([new_table]);
See also
- QScript for an explanation of how to run this code.
- QScript Examples Library for other examples.
- QScript Reference for technical information.
- JavaScript for information about the JavaScript programming language.
- Table JavaScript and Plot JavaScript for tools for using JavaScript to modify the appearance of tables and charts.
- JavaScript Variables for detail on how to create new variables in the Variables and Questions tab using JavaScript.