Calculated variable


The calculated variable question type is a powerful tool that lets you perform calculations within your survey and saves the result in your database. While they are listed as a question type, all analysis occurs behind the scenes, and they are entirely hidden from respondents.

How do calculated variables work?

Calculated variables let you create a calculation based on respondent answers and external variables, using either JavaScript or Conjointly formulas. Once a respondent reaches the stage in a survey where a calculated variable question is listed, the result of the variable is available for the remainder of the survey. This makes them available for displaying to respondents, survey flow controls, screening respondents and more.

After survey completion, the outputs are accessible in the Pivot table , Segmentation , and Weights report sections. They are also available for export as part of the raw data in SPSS, Excel, and R formats.

Example applications of calculated variables:

  • Calculating respondent age from their birth year.
  • Computing total household income from a variety of listed income streams.
  • Calculating a composite score from multiple questions, for example BMI based on respondent’s height and weight.
  • Estimating an insurance risk score, based on a variety of factors.
  • Assigning values to respondents based on random chance.
  • Creating a typing tool to classify respondents into different groups.

Value types of the calculated variable

The calculated variable can produce four types of values:

  • Number: Numerical values (e.g. 42, 3.14, -10).
  • String: Case-sensitive text values (e.g. "High", "not sure", "Category A").
  • Boolean: True or False.
  • Undefined: A special value when no value is calculated or returned.

Within the same question, different respondents or different stimuli can have different value types. For example:

Respondent IDStimulus IDQuestion IDValueValue type
123NULL1234NULLUndefined
1241234512351Number
125123451235"2a"String
124123461235TRUEBoolean
125123461235"2a3"String

Use as logic in segmentation and weighting

Calculated variables provide powerful logic capabilities for segmentation and weighting schemes. Here’s how you can leverage various operators:

Type checking operators

  • Value is of type “Undefined”
  • Value is of type “Number”
  • Value is of type “String”
  • Value is of type “Boolean”

String operators

  • Equal: Compares strings exactly, including case. Use when precise matching is required. For example, "Apple" equals "Apple", but not "apple".
  • Not equal: Checks if strings are different in any way, including case. Useful for exclusion criteria. For example, "Orange" is not equal to "orange" or "Banana".
  • Contains (regardless of lower or upper case): Searches for a substring within the text, ignoring case. Ideal for partial matches. For example, "Hello World" contains "world" or "WORLD".
  • Does not contain (regardless of lower or upper case): Verifies the absence of a substring, ignoring case. Useful for filtering out specific terms. For example, "Good morning" does not contain "night" or "NIGHT".

Number operators

  • Less: Checks if a value is strictly less than another. Useful for upper bounds. For example, age < 18 for a youth segment.
  • Less or equal: Verifies if a value is less than or equal to another. Suitable for inclusive upper limits. For example, score <= 50 for a low-performance group.
  • Greater: Determines if a value exceeds another. Useful for lower bounds. For example, income > 100000 for a high-income bracket.
  • Greater or equal: Checks if a value is greater than or equal to another. Suitable for inclusive lower limits. For example, experience >= 5 for senior-level segmentation.
  • Between: Verifies if a value falls within a specified range, inclusive of endpoints. Useful for defining brackets. For example, 25 <= age <= 34 for a millennial segment.
  • Not between: Confirms if a value is outside a specified range. Useful for excluding middle ranges. For example, age < 18 or age > 65 for non-working-age population.

Handling data type mismatches

When applying string or number operators to calculated variables, the system handles data type mismatches in specific ways:

Data type of the variableWhen using a string operatorWhen using a number operator
StringWorks as expectedConverts to a number if possible. If conversion fails, treats as 0
NumberConverts to text (e.g., 0.123"0.123"). Uses “.” for decimals, no scientific notationWorks as expected
BooleanConverts to "0" or "1"Converts to 0 or 1
UndefinedEvaluate the whole condition as FALSEEvaluate the whole condition as FALSE

Accessing calculated variables

After a calculated variable question is added to a survey, it is available to be used further stages throughout the questionnaire. For example, you are able to access the result of the calculated variable when setting up survey logic for subsequent questions.

Using a calculated variable for question logic

They are also available in your experiment’s report, under the Pivot table , Segmentation , and Weights tabs.

Calculated variables are stored in your experiment’s raw data, which can be exported in various formats, including Excel, which we’ll use in the following example.

Viewing calculated variables in Excel

  1. Open the exported Excel file.
  2. Navigate to the Answers to questions sheet.
  3. Locate the columns related to your calculated variables.

For each calculated variable, you’ll find two corresponding columns:

  • Answer type column, which indicates the data type of the stored value.
  • Answer column, which shows the stored value of the calculated variable.

Understanding how calculated variables are stored

Conjointly stores calculated variables in specific ways based on their data type:

Data type of the variableHow value is stored
StringStored as-is
NumberConverted to a string without any scientific notation or shortening. For example, 0.123 is stored as "0.123"
BooleanConverts to "0" (for false) or "1" (for true)
UndefinedStored as NULL

Other special cases to be aware of:

  • NaN (Not a Number): Stored as NULL, with type undefined
  • Infinity: Stored as the string "Infinity", with type number
  • -Infinity: Stored as the string "-Infinity", with type number

Adding a calculated variable question

To add a calculated variable question to your experiment:

  1. Navigate to the Add questions tab.
  2. Click on the Add question button at the bottom of the page.
  3. In the Add or import questions pop-out, select the Add a new question tab.
  4. Click on the Calculated variable question card.
Add calculated variable to survey

After adding the question, you can select either Formula or JavaScript in the Type field.

Calculated variable settings

Setting up calculated variables using a formula

If you select Formula as your input type, enter a valid formula in the Formula field to calculate your desired value. Here’s how to use the formula editor effectively:

  1. The editor will display a list of available formulas, similar to pipe-in formulas.
  2. Hover over each formula to see a tooltip explaining what the formula does, required inputs, and examples.
  3. Select the formula you want to add, and the editor will autofill the formula.
  4. Press the tab key on your keyboard to view available inputs.
  5. Click to add your desired input.

To help you construct effective formulas, Conjointly offers detailed guides covering various formula categories:

  • Respondent properties: Access respondents’ demographic and metadata with formulas like GETvariable and respondentInfo.
  • Respondent’s answers: Retrieve survey responses using functions such as answer and answered.
  • Rounding: Adjust numerical precision with ceil, floor, round, and toFixed.
  • Text formulas: Process string data using contains, startsWith, and endsWith.
  • Date and time: Convert a date and time presented in a ISO 8601 formatted string to number using toDateTime.
  • General functions and operators: Explore a wide range of additional functions and operators for diverse calculation needs.

These guides provide comprehensive information on available functions and operators, along with practical examples to help you create effective calculated variables.

Setting up calculated variables using JavaScript

For more complex calculations that exceed the capabilities of formulas, you can use JavaScript:

  1. Select JavaScript in the Type field.
  2. In the JavaScript field, define a test() function that returns your calculated value.

The basic structure of the JavaScript function is:

function test() {
    // Your calculation logic here
    return calculatedValue;
}

This setup is similar to the JavaScript used for conditional logic in survey questions. The test() function should contain your calculation logic and return the desired value.

Remember that you can access survey data and perform complex operations within this function to derive your calculated variable.

Example 1: Generate a random integer from 1 to 19

function test() {
  return Math.floor(Math.random() * 19) + 1;
}

Example 2: Categorise sum of slider values in the slider question Q6

function test() {
    let sum = $("#additionalQuestions6-frame").find(
        '[name^="additionalQuestions"][name*="[slider][items]"][type="number"]'
    ).toArray().map(x => Number($(x).val())).reduce((a, b) => a + b, 0);

    if (sum > 50) {
        return 'High';
    } else if (sum >= 25) {
        return 'Mid';
    } else {
        return 'Low';
    }
}