JavaScript Variables can be created for one data file using data from the other data file using Q.GetValue. The way that JavaScript variables work when being used in a data file with a One to many relationship with another data file is different to how JavaScript variables work elsewhere in Displayr. This is because the nature of a One to many relationship is that each observation in the individual-level database is related to multiple observations in the other database (e.g., one household may have made multiple purchases). Consequently, in these situations, JavaScript expressions that refer to variables in the situational database return an array (i.e., a list of values).
Requirements
A Displayr document with more than one data set connected by a data file relationship. See How to Edit Data File Relationships for more information.
Please note these steps require a Displayr license.
Method
1. In the Data Sources tree of the data set where you would like to insert the variable, hover between any two variables, then click + > Custom Code > JavaScript - Numeric.
2. Paste the following code into the Data > JavaScript Code expression:
var brand = Q.GetValue('brand', 'Transactions.sav');
brand.length != 0
This is interpreted as follows:
- Q.GetValue('brand', 'Transactions.sav') gets, for each observation in the individual-level database, the data in the variable called brand in the situational database (i.e., Transactions.sav). As mentioned, this is an Array. For example, if the household had made four purchases, of brands 3, 2, 1, and 1, then [3,2,1,1] would be returned.
- var brand = assigns the array to a variable called brand. (A variable in this context is temporary and does not create a variable called brand in the Data Sets tree.)
- brand.length computes the length of the array stored in the variable called brand (i.e., the number of values separated by commas).
- brand.length != 0 returns a 1 if the length of the array contains at least one entry and a 0 otherwise (i.e., it is a logical expression, and true is shown as 1 and false as 0).
You will need to update 'brand' and 'Transactions.sav' in the first line of code with the appropriate variable Name and data set name from your project.
3. Click Calculate.
4. Update the variable Name and Label from the General tab.
5. Update the Structure as necessary under General > Properties.
6. Update the Labels as necessary under General > Properties.