Relabel Variable and Value Labels

From Q
Jump to navigation Jump to search

This code adjusts the variable and value labels of specified questions in Q. In the below example we have updated the labels for two questions, d3 and q3. We first specify the value labels within 'value_info' and then set the variable label by specifying the variable name and the new variable text within the 'updateVariableLabels' function.

updateVariableLabels = function(variable_name, value_info, new_variable_label) {
	var variable = project.dataFiles[0].getVariableByName(variable_name);
	if (variable == null) {
		log(`There is no variable with name ${variable_name}`);
		return null;
	}
	var value_attributes = variable.valueAttributes;
	var unique_values = variable.uniqueValues;
	value_info.forEach(function (info) {
		if (unique_values.indexOf(info[0]) == -1)
			log(`Variable ${variable_name} does not have a value of ${info[0]} so the script skipped this value.`);
		else 
			value_attributes.setLabel(info[0], info[1]);
	});
	variable.label = new_variable_label;
}

// Edit code below

// d3

var value_info = [[1, "Male"],
				 [2, "Female"]];

updateVariableLabels("d3", value_info, "D3 - Gender")			

// q3

var value_info = [[1, "Coca-Cola"],
				 [2, "Diet Coke"],
				 [3, "Coke Zero"],
				 [4, "Pepsi"],
				 [5, "Diet Pepsi"],
				 [6, "Pepsi Max"],
				 [7, "Dislike all cola"]];

updateVariableLabels("q3", value_info, "Q3 - Preferred cola")

See also