Create New Variables - NPS Recoding

From Q
Jump to: navigation, search

This QScript looks for likelihood to recommend questions in your project and creates new variables that are recoded to display the NPS score. NPS questions are those questions which contain the words likely or likelihood in the question name, or whose value labels contain the string likely, and which are 11-point scales. 10-point scales are also recoded, however NPS scores strictly only apply for 11-point scales.

Technical details

Recoding is conducted based on numbers found in the category labels. Those categories whose labels contain numbers less than or equal to 6 (detractors) will be recoded with a value of -100, those categories whose labels contain a 7 or 8 (neutral) will be recoded to a value of 0, and categories with labels 9 or 10 (promoters) will be recoded to a value of 100. This produces an Average that is the NPS score.

Categories which look like standard Don't Know questionnaire options will be set as missing and will not be included in the calculation of the NPS.

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.


  • 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.


// Create New Variables - NPS Recoding

includeWeb('QScript Questionnaire Functions');
includeWeb('QScript Value Attributes Functions');
includeWeb('QScript Utility Functions');
includeWeb('QScript Selection Functions');
includeWeb('QScript Functions to Generate Outputs');

if (!main())
    log("QScript Cancelled.");
    conditionallyEmptyLog("QScript Finished.");

function main() {
    var allowed_types = ["Pick One", "Pick One - Multi"];
    var is_displayr = Q.isOnTheWeb();
    var selected_questions;
    if (is_displayr) {
        selected_questions =;
        if (selected_questions.length == 0) {
            log("No variable sets have been selected.");
            return false;

        var sorted_selection = splitArrayIntoApplicableAndNotApplicable(selected_questions, function (q) {
            return allowed_types.indexOf(q.questionType) != -1 && isLikelihoodScale(q, false);
        selected_questions = sorted_selection.applicable;
        var not_applicable_questions = sorted_selection.notApplicable;

        if (not_applicable_questions.length > 0) {
            log("The following variable sets can not be used because they do not have the appropriate format (e.g. contain an 11-point likelihood to recommend scale):");
            log( (q) { return; }).join("\r\n"));
            return false;
    } else {
        var selected_datafiles = dataFileSelection();
        var candidate_questions = getAllQuestionsByTypes(selected_datafiles, allowed_types);
        candidate_questions = candidate_questions.filter(function (q) { return isLikelihoodScale(q, true); } );
        if (candidate_questions.length == 0) {
            log("No 'likelihood to recommend' questions found.")
            return false;

        selected_questions = selectManyQuestions("The following questions look like 'likelihood to recommend' questions. Please select the ones you want to create new NPS variables for.", candidate_questions).questions;
        if (selected_questions.length == 0) {
            log("No questions selected.")
            return false;
    // Check that selected question is valid
    for (var i = 0; i < selected_questions.length; i++) {
        if (!selected_questions[i].isValid) {
            log("Variable '" + selected_questions[i].name + "' is invalid.");
            return false;
         var isEmpty = true;
         for (var j = 0; isEmpty && j < selected_questions[i].uniqueValues.length ; j++)
             isEmpty = !isFinite(selected_questions[i].uniqueValues[j]);
         if (isEmpty) {
              log("Variable '" + selected_questions[i].name + "' is empty.");
              return false;
    var nps_questions = [];

    for (var j = 0; j < selected_questions.length; j++) {
        var question = selected_questions[j];
        var new_q_type;
        if (question.questionType == "Pick One")
            new_q_type = "Number";
            new_q_type = "Number - Multi";

        var new_q = question.duplicate(preventDuplicateQuestionName(question.dataFile, + " - NPS"));
        new_q.questionType = new_q_type;

    if (is_displayr) {
        log("The following variable set(s) were added:");
        log( (q) { return}).join("\r\n"));
        log("In addition, page(s) named 'NPS Variables' containing their summary tables have been added to the document.")

    var new_group = generateGroupOfSummaryTables("NPS Variables", nps_questions);
    new_group.subItems.forEach(function (item) {
        if (item.type == "Table") {
            var trans = item.translations;
            trans.set("Average", "NPS");
    conditionallyEmptyLog("New NPS variables have been added to the folder: NPS Variables");

    return true;

function npsRecode(question) {

    // check for DK labels and set as missing
    var unique_values = question.uniqueValues;
    var value_attributes = question.valueAttributes;
    unique_values.forEach(function (x) { 
        if (isDontKnow(value_attributes.getLabel(x)))
            setIsMissingDataForVariablesInQuestion(question, x, true);

    var non_missing_labels = nonMissingValueLabels(question);
    var quantified_labels =;
    // If the first or last label can't be quantified by the usual means
    // (ie because it doesn't have a number and is just something like
    // "Not very likely") then work out the correct value by looking at the
    // adjacent value.
    if (isNaN(quantified_labels[0]))
        quantified_labels[0] = quantified_labels[1] - 1;
    if (isNaN(quantified_labels[quantified_labels.length - 1]))
        quantified_labels[quantified_labels.length -1 ] = quantified_labels[quantified_labels.length - 2] + 1;
    var non_missing_source_values = nonMissingSourceValues(question);
    var source_value;
    var new_value;
    for (var j = 0; j < non_missing_labels.length; j++) {
        source_value = non_missing_source_values[j];
        if (quantified_labels[j] <= 6)
            new_value = -100;
        else if (quantified_labels[j] > 8)
            new_value = 100;
            new_value = 0;
        setValueForVariablesInQuestion(question, source_value, new_value);
function nonMissingSourceValues(question) {
    var unique_values = question.uniqueValues;
    var value_attributes = question.valueAttributes;
    return unique_values.filter(function (v) {return !value_attributes.getIsMissingData(v); });

See also