QScript Scale Functions

From Q
Jump to navigation Jump to search

The functions below are used by the scaling QScripts under Create New Variables - Scale Within Case and Create New Variables - Scale Within Variable.

To make these functions available when writing a QScript or Rule see JavaScript Reference.

scaleOneQuestion(question, type, within_case)

This function takes one QScript Question and performs a scale transformation to it. See the next function for a description of the type and within_case arguments.

scaleQuestions(type, within_case)

This function uses variable sets selected by the user in Data Setsprompts the user to select questions and performs a scale transformation to each selection based on the type argument. Possible values for type are "rank", "standardize", "center", and "unit". If within_case is true, then the scaling is performed within case/respondent; otherwise, it is performed within variable. This is a wrapper for scaleOneQuestion.

Source Code

includeWeb("QScript Utility Functions");
includeWeb("QScript Selection Functions");
includeWeb("QScript Functions to Generate Outputs");
includeWeb("QScript R Output Functions");

function scaleVariables(variables, type, within_case) {
    const is_displayr = inDisplayr();
    const structure_name = is_displayr ? "variable set" : "question";
    const questions = variables.map(v => v.question).filter(onlyUnique);
    const data_file = getDataFileFromQuestions(questions);


    const input_name = constructNameForVariables(variables);
    let new_question_name = (type === "unit" ? "unit scale" : type) + " within " +
        (within_case ? "case" : "variable") + " for " + input_name;

    function capitalizeFirstLetter(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
    }

    new_question_name = capitalizeFirstLetter(new_question_name);
    new_question_name = preventDuplicateQuestionName(data_file, new_question_name);
    let temp_var_name = randomVariableName(16); // temporary name, random to (almost) guarantee uniqueness

    if (variables.length === 1) {
        if (within_case) {
            log('Scaling within case for ' + structure_name + ' ' + input_name + ' is not meaningful ' + 'since it consists of only a single variable.');
            return false;
        }

        if (variables[0].variableType === "Date" && type != "rank") {
            log('The selected scaling type is not meaningful for Date variables. The only scaling which can be applied for ' + input_name + ' is Ranks Within Variable.');
            return false;
        }
    }

    const refs = variables.map(v => checkDuplicateVariable(v.name) ? generateDisambiguatedVariableName(v) : stringToRName(v.name));
    const data_name = "inputs";
    let data_reference = "";
    if (variables.length === 1) {
        data_reference = data_name + " <- " + refs[0] + "\n";
    }
    else {
        let expr_name = [];
        for (let i = 0; i < variables.length; i += 1) {
            expr_name[i] = stringToRName(getVariableLabelWithOptionalPrefix(variables[i])) + " = " + refs[i];
        }
        const expr_prefix = data_name + " <- data.frame(";
        const white_space = " ".repeat(expr_prefix.length);
        data_reference = expr_prefix + expr_name.join(",\n" + white_space) + ",\n" +
            white_space + "check.names = FALSE)\n";
    }
    const expression = data_reference + "flipTransformations::ScaleVariableSet(" + data_name + ', type = "' + type +
        '", within.case = ' + within_case.toString().toUpperCase() + ")";

    let new_r_question;
    try {
        new_r_question = data_file.newRQuestion(expression, new_question_name, temp_var_name, variables[variables.length - 1]);
        insertAtHoverButtonIfShown(new_r_question);
    }
    catch (e) {
        function errorFun(e) {
            log("The transform could not be computed for " + structure_name + " " + input_name + " : " + e.message);
            return false;
        }
        return errorFun(e);
    }

    // Replace temporary variable names
    nameSequentialVariables(new_r_question.variables, "scaled");
    let top_group_name = type.slice(0, 1).toUpperCase() + type.slice(1) + (type == "unit" ? " scale " : "") +
        " within " + (within_case ? "case" : "variable") + " Transformation";
    reportNewRQuestion(new_r_question, top_group_name);
    return true;
}

function scaleQuestions(type, within_case) {

    let allowed_types = ["Nominal - Multi", "Ordinal - Multi", "Numeric - Multi", "Numeric - Grid"];
    let variables = selectInputVariables(allowed_types);

    if (!variables || variables.length === 0) {
        return false;
    }
    return scaleVariables(variables, type, within_case);
}

See also