Sometimes when you are working with consumption data, you may want to analyze the "Share of" particular brands. This could be share of wallet, spend, mouth, etc. For an automated solution to the same problem, see Create New Variables - Case-Level Shares. However, you can also set this up manually with a JavaScript variable.
Technical details
This method is also known as the unweighted formula for volumetric analysis. You can read the comments in the code to see what each line does. The code below is assuming you are analyzing using categorical data for the product across different questions. For example, to compute a share of wallet measure for each respondent, based on the number of products that a customer holds where the products’ holdings are in four variables q1c, q5a, q11b and q23. Further, let us assume that in each of these product variables, a 5 equates to your client’s brand and a NaN indicates the customer does not have the product.
Key features to note about this example are:
- var a = new Array creates a new array which initially contains nothing (an array is a list of objects, such as numbers).
- !isNaN returns a true if a it is not a missing value (i.e., ! indicates not).
- a.push appends something to the array called a, increasing its size.
- q1c == 5 returns a value of true if q1c is equal to 5 and false otherwise; this is equivalent to returning a value of 1 or 0.
- a.length returns the number of entries in the array called a. Note that in this example this number will differ depending upon the number of products that the user has.
- A new variable, result, is initialized with a value of 0.
- A for loop is used to loop through all the contents of the array, first making i take a value of 0, then 1, etc.
- a[i] returns the first entry of the array when i is 0, the second when i is 1, etc.
- += indicates that the value if a[i] is added to result. It is equivalent to writing result = result + a[i].
- If we wanted to reuse this code at a later stage, we could do so by modifying only the lines of code beginning with if (!isNaN).
Method
We can compute the share of wallet in this instance as follows:
//create a new empty array to hold info about choices
var a = new Array;
//for each question - if it's not blank - test to see if the value is equal to the product
//and add it to the array. The array will be a lot of Trues and Falses if (!isNaN(q1c)) a.push(q1c == 5); if (!isNaN(q5a)) a.push(q5a == 5); if (!isNaN(q11b)) a.push(q11b == 5); if (!isNaN(q23)) a.push(q23 == 5);
//if the array is empty that means that all the questions had missing data if (a.length == 0) {
//return missing value NaN;
//else we can calculate share } else {
//create variable to hold result var result = 0;
//for each item in the array, add it to the result (True will count as 1 False as 0) for (var i = 0; i < a.length; i ++) result += a[i];
//finally calculate the share of the product based on how many of the questions were answered result / a.length; }