This article illustrates how you can create a crosstab within JavaScript. That can be useful in situations where you are computing variables that need to depend upon tabulated results. For example, if you want to use JavaScript to automatically compute weights in a data file (although this is generally better done in Displayr using Weighting).
The left-hand side shows the standard table. The right side shows the same table, but created as a JavaScript variable with Access all data rows ticked in the object inspector (just beneath the JAVASCRIPT CODE expression box), where the table has essentially been flattened (lines illustrate the relationship for the first four cells in the table).
Method
1. In the Data Sets tree, hover between two variables and click + > Custom Code > JavaScript - Numeric.
2. Paste the following syntax into the JAVASCRIPT CODE expression box:
var gender = Q2; var age = Q3; var result = new Array(N); for (var i = 0; i < N; i++) { var category = gender[i] + (age[i] - 2) * 2; if (isNaN(result[category])) result[category] = 0; result[category]++; } result
3. Tick Access all data rows.
4. Update the Structure to Nominal: Mutually exclusive categories.
5. Give the variable a Name and Label.
You can view the raw data of the new variable by right-clicking it in the Data Sets tree and selecting View in Data Editor.
A few things to note about this example:
- The net effect of gender[i] + (age[i] - 2) * 2 is to compute a value for each respondent, where the value computed is 1 when they are male and aged 18 to 24, 2 when they are female and aged 18 to 24, 3 when they are male and aged 25 to 29, etc.
- A more elegant implementation would create a two-dimensional array rather than writing the result out to a variable. If it is not clear what this means or how to do it, find an online course on using arrays in JavaScript.
- The -2 is because the age variable has a lowest value of 2. If it had a lowest value of 1, then one could use -1 instead. Strictly, there is no need to subtract the value, as all it does is control the number of NaNs appearing at the beginning of the Result column.
- The arrays used to represent variables when using Access all data rows start at 0. Thus, the result computed when category is 1 appears as the second observation in the resulting variable.
Next
How to Use JavaScript in Displayr