This article illustrates how you can create a crosstab within JavaScript. That can be useful in the situations where you are computing variables that need to depend upon tabulated results. For example, if wanting to use JavaScript to automatically compute weights in a data file (although this is generally better done in Q using Weighting).
The left-hand side shows a standard table created by Q. The right side shows the same table, but created as a JavaScript variable using Access all data rows (advanced), where the table has essentially been flattened (arrows illustrate the relationship for the first four cells in the table).
Method
This example uses the Cola.Q project that comes with Q. The syntax is:
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
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 (advanced) start at 0. Thus, the result computed when category is 1 appears as the second observation in the resulting variable.
Next
How to Create Text Variables Using JavaScript
How to Work with Conditional JavaScript Formulas