It’s easier than you think to use basic JavaScript to create new variables! The following worked example in Displayr shows you how to combine, split, and transform data into new variables using conditional ‘if’ statements and Boolean logic (“and”, “or”).

When to create JavaScript variables instead of R variables in Displayr

JavaScript code is all ran through your browser. This means that you don't need to package up data and code to be processed on our R servers. While usually there isn't a noticeable difference between creating a basic JavaScript variable versus R, if your data is quite large and you're doing a simple manipulation on it, it may be faster to use JavaScript. If your new variable requires more advanced calculations and coding, it may be easier or only possible to create it using R, which was designed specifically to do analysis (unlike JavaScript). Just like R variables, JavaScript variables are updated automatically in the project, and you can also easily go back to edit variables if you want to tweak the code.

How to create JavaScript variables in Displayr

Create a JavaScript variable via the Ribbon in Displayr (Insert > JavaScript > Numeric Variable). You have a choice of creating a Numeric or Text variable. For simplicity, let’s consider only numeric variables for now.

A new variable will appear in the Data Sets panel, and the JavaScript expression can be entered into the JavaScript Code box in the Object Inspector. An example is shown below:

You need to write (or paste) a JavaScript expression using variable Names (not labels). Hovering over a variable in the Data Sets panel will show the variable name. You can also click-and-drag the variable into the text box to paste the variable name.

A worked example

In our example, we have collected consumption data on six different sub-types of cola. This forms six different numeric variables. The following JavaScript expression finds the sum of the variables with JavaScript: q2a_1 + q2a_2 + q2a_3 + q2a_4 + q2a_5 + q2a_6.

These are referred to as the input variables. You can see a preview of the new variable beside the JavaScript Code box and check that your expression is working correctly.

You can manually check the first few lines to confirm that your JavaScript expression works as expected.

Banding a numeric variable

Suppose the expression in the above example resulted in a new numeric variable that we called “sumCola”. Now we want to create an additional variable that allocates people to one of three categories based on their total cola consumption (Light Drinkers – less than 5 colas, Medium Drinkers – between 5-10 colas, and Heavy Drinkers – more than 10 colas).

The if command allows you to do this:

if (sumCola < 5) 1; 
else if (sumCola>= 5 && sumCola <= 10) 2; 
else if (sumCola > 10) 3; 
else NaN;

 

The code can be interpreted as follows:

if (sumCola < 5) 1;

If the variable sumCola is less than 5, return a value of 1.

else if (sumCola>= 5 && sumCola <= 10) 2;

If the expression above does not apply, and if the variable sumCola is greater than or equal to 5 and (represented by &&) less than or equal to 10 (i.e., falls between 5 and 10), return a value of 2.

else if (sumCola > 10) 3;

If the expressions above do not apply, and if the variable sumCola is greater than 10, return a value of 3.

else NaN

Consider any other values as missing. NaN stands for Not-A-Number (i.e., missing or blank)

The newly created variable will have the values of 1, 2, or 3 (and perhaps NaN). Because we want this to act as a categorical variable, we have to add two extra steps. Click on the variable and make the following changes in the Object Inspector:

  1. Change the Structure to Nominal: Mutually exclusive categories.
  2. Click the Labels button and give the variable more descriptive labels (e.g., 1 = “Light Drinker”, 2 = “Medium Drinker” and 3 =  “Heavy Drinker”).

You can create the same bandings by merging columns in a table. However, when you import new data, new values may need to be manually merged into one of the three categories. The beauty of using the JavaScript variable is that it automatically allocates new results to the appropriate category.

You could also combine all the above into a single variable, rather than splitting it over two. This can be done by creating variables within the JavaScript variable. In the following example, we create a new variable within the JavaScript variable called x:

var x = q2a_1 + q2a_2 + q2a_3 + q2a_4 + q2a_5 + q2a_6;
if (x > 5) 1;
else if (x <= 5 && x >= 10) 2; 
else if (x < 10) 3; 
else NaN;

Combining different weighting variables

In the above examples, the JavaScript variables are returning constant values. But JavaScript variables can return the values of other variables as well. A common application is the need to combine the weights for various segments into one variable.

Consider a situation where we’ve collected data for four countries: UK, France, Australia, and Japan. The data for each country was held in 4 separate data files and merged into a final file. Membership to a particular segment (market) is defined by a variable called country. Each country’s data file had a specific weighting variable, so we now have four different weighting variables in the merged data file (weight_UKweight_FRweight_AUweight_JP). When we do our analysis, we only want to deal with one weighting variable. So let’s combine them using JavaScript:

 
if (country == 1) weight_UK; 
else if (country == 3) weight_FR;  
else if (country == 7) weight_AU;
else if (country == 4) weight_JP; 
else NaN; 

 

You’ll notice that there are two consecutive equals signs in the above expression. You need both of them because a single equals sign has a different role in JavaScript. In short, a single equals sign is used for assignment while the double-equals sign tests for equality.

When setting a variable as something (also called assigning a value), as in the example above with the variable called x, use the single equals sign. When testing for equality, as in the example above with the expression country == 3, use the double-equals sign.

You may also notice that the values of the country variable are not sequential. That’s because, in our hypothetical example, the variable country has values of 1 = UK, 2 = Germany, 3 = France, 4 = Japan, etc.

Making a date variable from a categorical variable

In Displayr, JavaScript (like R) has a suite of ready-made functions that can help you do great things. One such function is Q.EncodeDate(). It will enable you to return a number in a format that Displayr can, in turn, recognize as a date question. When used in conjunction with conditional statements, you can turn a categorical variable (e.g. period or wave variable) into a date question. Date questions have numerous benefits in Displayr, such as automatic aggregation of time, testing (significance) against the previous period, specific filter functions, and more.

Suppose you have a variable in your data file called week that encodes the week of the survey in categorical format. As a result, it just encodes values: 1 = week one, 2 = week two, 3 = week three, and so on. You can turn this into a date question, starting the first week on the 1st Jan 2018, using an expression like the one below. Notice that Q.EncodeDate works with the YYYY,MM,DD format.

 
if (week == 1) Q.EncodeDate(2018,01,01); 
else if (week == 2) Q.EncodeDate(2018,01,08); 
else if (week == 3) Q.EncodeDate(2018,01,15); 
else if (week == 4) Q.EncodeDate(2018,01,22); 
else if (week == 5) Q.EncodeDate(2018,01,29); 
else if (week == 6) Q.EncodeDate(2018,02,05); 
else NaN; 

 

Then change the variable structure to Date/Time to use it as a date variable set.

Working with JavaScript text variables

JavaScript text variables are useful if you want to join the results of different open-ended variables. The following expression joins three spontaneous brand awareness questions into a single text variable and inserts punctuation. It is akin to the concatenate function in Excel.

q1a_1 + ", " + q1a_b + ", " + q1a_c + "."

If you aim to create create a categorical variable, as in the first example with Light-Heavy drinkers, then you can use a text JavaScript variable to generate the labels. Displayr automatically sets up value labels when converting a text variable to a categorical variable.

If you create a numeric variable, you may need to manually assign labels to the values (e.g., 1 = Segment A, 2 = Segment B) as per the first example in this post. The first example (summing the colas) can be rewritten as a text variable with the following:

if (sumCola > 5) "Light Drinker";
else if (sumCola <= 5 && sumCola <= 10) "Medium Drinker"; 
else if (sumCola > 10) "Heavy Drinker";
else "";

Tips when working with code

Writing in computer code needs to be exact – you need to pay attention to:

  • The presence or absence of semi-colons: they signal that you’re ready for the next bit of the expression.
  • The capitalization of letters: case-sensitivity means that “if” does not mean the same as “If” or “IF”.
  • The right number of brackets (and where they open/close)
  • Whether brackets are (round) or {curly} or [square].
  • When symbols are doubled: double ampersands (&&) for “AND”, double-equal signs (==) for equality, and double pipes (||) for "OR".
  • Missing values with your input variables: they can lead to missing results if not handled correctly. There is a more elaborate code you can use to make conditional statements around missing values.