Introduction
Determining the highest rated item within a set of questions involves creating a variable that examines the responses of each respondent, and identifies the question with the highest value. This can be done in Q with just a few lines of JavaScript code.
For this worked example, we are using data from a tracking study on cola consumption habits. We have consumption data on six types of colas — Coca-Cola, Diet Coke, Coke Zero, etc — and we want to determine the most-consumed beverage for each survey respondent.
Method
Step 1: Create a JavaScript variable
The first step is to create a new variable. In the Variables and Questions tab, right-click anywhere within the window and
- select Insert Variable > JavaScript Formula > Numeric.
This will open a pop-up box where you can create your variable using JavaScript.
Step 2: Write your JavaScript expression
Now it’s time to write your JavaScript expression. The consumption information for our six colas is stored in the q2b questions (q2b_1, q2b_2,…,q2b_6). The most-consumed cola for each survey respondent is the highest value of the six variables. The following three lines of JavaScript can be used to locate the highest value. Note if there is a tie, the code will return the location of the first of the highest values in your list. The final variable will be a list of numbers of the locations of the most consumed cola from your list.
var x = [q2b_1, q2b_2, q2b_3, q2b_4, q2b_5, q2b_6]
max = Math.max(q2b_1, q2b_2, q2b_3, q2b_4, q2b_5, q2b_6)
x.indexOf(max) +1;
- Line 1 creates an array of the variables we want to analyze.
- Line 2 finds the largest of the given values.
- Line 3 locates the position of the largest value.
Step 3: Change the question type of the new variable
In the Variables and Questions tab, change the Question Type to Pick One. This will allow you to analyze the question as a categorical variable rather than a numeric variable.
If you wish, you can rename the numbers to the corresponding cola based on the order of variables in your JavaScript code. From a table of your new variable, right-click and select Values, type in the cola names in the Label column, and click OK.