Modify Labels - Add Variable Names and Values to Labels

From Q
Jump to navigation Jump to search

This QScript adds extra information about variables into labels so that it can be seen on tables. The modifications include:

  1. Adding the variable name to the label of each variable.
  2. Adding the current values of categories to the category labels shown on tables.
  3. Adding information from the variable names to the corresponding question name.

In general, this QScript should be run immediately prior to exporting or printing. Once data exporting/printing has been completed, the variable names and labels should then be removed using Modifying Labels - Remove Variable Names And Values From Labels. Otherwise, standard operations, such as merging categories, will have ugly and difficult-to-fix outcomes. Alternative ways of getting similar information from Q without running this QScript, including:

Example

The table below shows how the Age question is modified by this QScript. The variable name, q4 has been added to the name of the question, and each of the categories in the rows of the table now features the value or values to which the category currently corresponds in the Value Attributes. That is, the category 15 and under corresponds to a value of 1, the category 16-24 yrs is formed by merging categories 16-19 yrs and 20-24 yrs, which have values of 2 and 3 respectively, and so on.

AgeNameValueAddition2.PNG

The next table shows how the Unaided Awareness question is modified by this QScript. The question name has been modified and the row labels now begin with the name of the variable that corresponds to each row.

AwarenessNameValueAddition1.PNG

Technical details

This script modifies:

  1. Question names for all questions.
  2. Variable Labels for all questions.
  3. Category labels for values for Pick One and Pick One - Multi questions.
  4. Category labels for variables for Pick One - Multi, Pick Any, and Number - Multi questions.

The modifications affect any NETs and merged categories that you have created in Q, but do not affect the original NET and SUM rows and columns that are placed on all tables by default.

When the script modifies these labels it uses a special invisible character in the text to denote the position of the original label. This allows you to use the companion QScript, Modifying Labels - Remove Variable Names And Values From Labels to remove the extra information from the labels again, as this script looks through the labels for the special invisible character.

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

// Modifying Labels - Add Variable Names And Values To Labels
includeWeb("QScript Functions to Generate Outputs");

if (!main())
    log("QScript Cancelled.");
else
    conditionallyEmptyLog("QScript Finished.");
 
function main() {
    includeWeb("QScript Utility Functions");
 
    var hidden_char = "\u200b ";
 
    project.dataFiles.forEach(function (data_file) {
        data_file.questions.forEach(function (question) {
                        if (!question.isBanner && question.isValid)
                addVariableNamesAndValuesToLabels(question, hidden_char);
        })
    });
    return true;
}
 
 
// This function modifies the question to:
// 1. Add the variable name to the question name. When the question has
//    more than one variable, the common prefix of the variable names
//    is used.
// 2. Add values to the category labels in the data reduction (Pick One
//    and Pick One - Multi questions only).
// 3. Add variable names to the variable labels and corresponding category
//    labels in the data reduction (Pick One - Multi, Pick Any, and 
//    Number - Multi questions only).
//
// Label modifications are separated from the original labels using a
// hidden character to make it easy to remove the modification using
// another QScript
function addVariableNamesAndValuesToLabels(question, hidden_char) {
    var variables = question.variables;
    var data_reduction = question.dataReduction;
    var question_type = question.questionType;
 
    // Add Variable Name to Question Name
    if (variables.length == 1)
        question.name = variables[0].name + hidden_char + question.name;
    else {
        var prefix = longestCommonPrefix(variables.map(function (v) { return v.name; }));
 
        // Remove non-alphanumeric characters at the end of the prefix
        while (prefix.length > 0 && prefix.substring(prefix.length - 1, prefix.length).search(/[A-Za-z0-9]/) == -1)
            prefix = prefix.substring(0, prefix.length - 1);
        if (prefix.length > 0)
            question.name = prefix + hidden_char + question.name;
    }
 
 
    // Add Values to Category Labels (Pick One, Pick One - Multi)
    if (question_type.indexOf("Pick One") == 0) {
        var value_attributes = question.valueAttributes;
        var by_columns = (question_type == "Pick One - Multi" && data_reduction.transposed);
        var codes = by_columns ? data_reduction.columnLabels : data_reduction.rowLabels;
        if (codes != null) {
            // Don't add for main table NET/SUM
            var net_indices;
            if (fileFormatVersion() > 8.65)
                net_indices = by_columns ? data_reduction.netColumns : data_reduction.netRows;
            else {
                net_indices = [];
                codes.forEach(function (code, ind) {
                    if (code == "NET" || code == "SUM")
                        net_indices.push(ind);
                });
            }
                
            // Rename codes
            codes.forEach(function (code, ind) {
                if (net_indices.indexOf(ind) == -1) {
                    var vals = data_reduction.getUnderlyingValues(code)
                                             .map(function (x) { return value_attributes.getValue(x); })
                                             .sort(function (a, b) { return a - b; });
                    data_reduction.rename(code, vals.join(",") + hidden_char + code);
                }
            });
        }
    }
 
 
    // Add Variable Names to Variable Labels (and corresponding data reduction labels)
    variables.forEach(function (v) {
        v.label = v.name + hidden_char + v.label;
    });
 
    var mr_types = ["Pick One - Multi", "Number - Multi", "Pick Any"]
    if (mr_types.indexOf(question_type) > -1) {
        var by_columns = (question_type == "Pick One - Multi" && !data_reduction.transposed);
        var codes = by_columns ? data_reduction.columnLabels : data_reduction.rowLabels;
 
        // Don't add for main table NET/SUM
        var net_indices;
        if (fileFormatVersion() > 8.65)
            net_indices = by_columns ? data_reduction.netColumns : data_reduction.netRows;
        else {
            net_indices = [];
            codes.forEach(function (code, ind) {
                if (code == "NET" || code == "SUM")
                    net_indices.push(ind);
            });
        }
 
        codes.forEach(function (code, ind) {
            if (net_indices.indexOf(ind) == -1) {
                var vnames = data_reduction.getUnderlyingVariables(code).map(function (v) { return v.name; });
                data_reduction.rename(code, vnames.join(",") + hidden_char + code);
            }
        });
    }
}

See also