Although Displayr automates the creation of the most commonly required variables, sometimes there's a need to create a new variable using custom JavaScript code.
Requirements
- Comfort with JavaScript code. See JavaScript Fundamentals if you're new to JavaScript or new to working with it in Displayr.
- Familiarity with Variable Set Structures and Value Attributes, see Variable Sets.
Method
- In the Data Sources tree, hover over any variable and click + > Custom Code > JavaScript > and select the structure of the variable you want to create. See Variable Set Structures & Question Types for more information about variable set structures.
- Enter your JavaScript code into the code editor window.
-
Click the Calculate button to run the code and create the JavaScript variable.
Note, if you first select a variable in your Data Sources tree, the new variable will be added directly below.
On the General tab, update Name and Label as appropriate.
You can then update the labels by selecting Data > Properties > Labels.
OPTIONAL: If the result is binary (0 or 1) and you wish to use this variable as a filter, tick Usable as a filter.
OPTIONAL: If the result is numeric and you wish to use this variable as a weight, tick Usable as a weight.
OPTIONAL: Tick Data > JavaScript Code > Access all data rows if you wish to work with arrays. The result must also be an array.
OPTIONAL: Tick Data > JavaScript Code > Accelerate (skip logic checks) to run your variable faster, particularly when your code is simple. In this case, you must first ensure you initialize all local variables before use. For example, write
var sum = 0;instead ofvar sum;.
Next
How to Use JavaScript in Displayr
How to Work with Conditional JavaScript Formulas