Automatically Recoding Midpoints

From Q
Jump to navigation Jump to search

This code automatically interpolates midpoints from a categorical variable (e.g., 18 to 24, 25 to 34 and 35 to 44). Where only one number appears in a label (e.g., 65 or more) then that number is used as the midpoint. Where no numbers appear in the label, the category is set to missing values.

To use this code you will need to create a new JavaScript Variable, paste the code into the Expression field and modify the first line so that it refers to the variable being recoded. You can also change the delimiters that are used in the second line. Note that that if you change the labels on the input variable, the recoding will automatically update. Also note that while this may look like a lot of code, it has been deliberately written in a rather lenthy way to illustrate how you can create expressions by cutting and pasting various functions together (see JavaScript Examples Library for more examples).

var label = Q.Label(AD09N1_2);//extracting the label
var delimiters = [" to ", "-"];

function AsNumber(x) {return parseFloat(x.replace(/[^0-9.-]+/g, ''))};// a function that extracts the number from a string
function AsNumbers(x) {//converts an array of strings into an array of numbers
    var numbers = [];
    for (var value in x)
return numbers;}
function MidPoint(array) {//averages any 2 (or 1) numbers in an array
    if (array.length == 1) return array[0];
    return (array[0] + array[1])/2.0;} //comæuting the midpoint
function AsArray(input_string, delimiters) { //a function for turning a string into an array
    var counter = 0;
    var array = []; 
    while (counter++ <= delimiters.length && array.length < 2) //stops when an array of 2 or more entries is found
        array = label.split(delimiters[counter-1]); //splitting into an array
    return array;}    
MidPoint(AsNumbers(AsArray(label, delimiters)))

See also

Create New Variables - Numeric Variable(s) from Code/Category Midpoints for a QScript which automatically recodes all the variables in a data file.