This article describes how to create a custom QScript in Displayr via the built-in QScript editor.
Requirements
Please note these steps require a Displayr license.
- A Displayr Enterprise user license which includes the ability to add custom analysis menu items
- The Colas.sav file which we will use for this article
Method - How to write your own QScript
Step 1: Plan
The first step is to work out whether a QScript is appropriate for the task you want to perform. In general, the benefit of a QScript is that it can replace a series of repetitive tasks, especially when this process will be repeated. Ask yourself, is there already a similar script or example code that I can use or modify? If you are unsure of this approach, please contact Support at support@displayr.com.
When working out whether a custom QScript is appropriate, outline what you need to do. Some questions to consider:
- Is the QScript intended to be used again?
- How flexible does this script need to be?
- Is it for a specific scenario only or does it need to be applied to different situations?
- Could a user potentially apply it to the wrong type of data or output?
- Is it possible to provide user prompts for all necessary options?
Example:
Below we have a data set that displays the question text shown in our survey but not the question number, i.e. Q1, Q2 etc.
We could manually amend these labels but this could also be automated via QScript. Let's look at a short example of a QScript that updates the variable set Label to include the variable Name so we get d1 - Age, for example, instead of just Age.
Now, what if we also want to allow the user to control which variable sets we apply this to? What about when we only want part of the prefix from the variable name to be included? The below will take us through the various steps to consider when creating a custom QScript using this example as a guide.
Step 2: Open the QScript Editor
From the toolbar, go to Anything > [Company name] > Open QScript Editor.
See How to Use QScripts in Displayr.
Step 3: Add the relevant JavaScript library
If you intend to use functions from some of our online libraries then this needs to be referenced upfront using the includeWeb
function and the name of the library:
includeWeb("QScript Selection Functions");
See Online JavaScript Libraries for details on the various libraries and functions available for QScripts. Here, we will include the QScript Selection Functions library as we will use a selection function that requires this.
Step 4: Declare your key variables
If you are working with data sets, variables, tables, or other objects, you will need to first declare these before writing the bulk of your code. This is also a good way to work out what you potentially will need to write in your code.
In our example, we will need to loop through each variable set so the key variables to declare in this case are the variable sets, the data file they come from, and the number of iterations for our loop:
var questions = project.dataFiles[0].questions; // get all variable sets
var n_questions = questions.length; // number of variable sets
-
questions
stores all variable sets orquestion
objects in our data set. -
n_questions
useslength
to find the number of items inquestions
to loop through.
See JavaScript Fundamentals and How to Work with Variables via QScript.
Step 5: Add selection options and input controls
When a QScript is going to be used repeatedly and needs to be flexible, selection options and input controls can offer an easy way to allow the user to select the options they want to apply.
Options include:
- Current selections
- Variable (set) selections
- Numeric and text fields
- List boxes
Generally, the workflow would be to declare the variable sets first and then populate a user control with these to choose from. In our example, however, we have decided we don't wish to simply run the script on all variable sets, but also allow users to run this only on specific variable sets as well.
In this case, we can replace the below...
var questions = project.dataFiles[0].questions; // get all variable sets
...with the following which uses the getAllUserSelections()
function from the QScript Selection Functions library:
var user_selections = getAllUserSelections();
var questions = user_selections.selected_questions;
- The
selected_questions
property returns all thequestion
objects within the selection. The data set does not need to be declared as this is already taken into account with the user selection. Note, the equivalent for thevariable
object isselected_variables
. - By default, this will run on all selected variable sets when a data set is selected in the Data Sets tree. Otherwise, it will run on the items selected within your Data Sets tree.
See How to Create User Input Prompts in QScripts.
Step 6: Write your main script
The main part of your code should appear here. In our example, this will include looping through the variable sets in your data set and modifying them.
Here, we place the code that does the actual work of renaming the variable set labels:
// loop through each variable set
for (var i = 0; i < n_questions; i++) {
var q_label = questions[i].name; // get variable set label
var var_name = questions[i].variables[0].name; // name of first variable in variable set
questions[i].name = var_name + " - " + q_label; // set variable set label
}
- We use a
for..loop
that loops through every variable set and returns their Label asq_label
and the first variable name asvar_name
. -
questions[i].name
then sets the variable set label by adding the variable name to the existing label.
See How to Work with JavaScript Arrays and Loops, How to Modify Variables and Value Attributes via QScript, and How to Create Custom Variables via QScript.
For other worked examples, see also How to Create a Banner via QScript, How to Add Pages, Folders, and Headings via QScript, How to Create Tables and Calculations via QScript, How to Create a Visualization via QScript, and How to Modify Tables via QScript.
Step 7: Add validations and messages
Validations can be performed to check, among others, whether:
- The input selections match the requirements of the script.
- Any user prompts contain valid inputs.
- The variable set structure of the input questions requires different code or is not appropriate.
Messages can similarly be used to:
- Notify users if there is an issue with their inputs.
- Notify users that the script has finished.
For example, we may wish to deal with situations where the variable set is a grid-style question and the first variable name contains extra characters that we don't wish to include, such as "_1" in Q5_1. This validation can be as complex and flexible as you want, but here we will simply restrict the variable name to 3 characters using substring
and replace "_" with a blank:
var_name = var_name.substring(0,3).replace("_","");
This line needs to be added directly before the last row within the loop which re-sets the variable name.
As an aid to the user, we can also add a log message at the end to say when the script has finished:
log("Your variable set labels have now been updated");
See How to Create Diagnostic Messages and Perform Validations via QScript and How to Manipulate Strings Using JavaScript.
Step 8: Write any custom functions (optional)
Custom functions can help with simplifying the bulk of your code, especially when performed in multiple places. Functions can be added anywhere in the code, but for readability, it is often easier to place these at the bottom so the main part of the code is more accessible.
We will now update our loop code so you can see it as a custom function:
for (var i = 0; i < n_questions; i++) {
addVariableNameToLabel(questions[i]);
}
function addVariableNameToLabel(question) {
var q_label = question.name; // get variable set label
var var_name = question.variables[0].name; // name of first variable in variable set
var_name = var_name.substring(0,3).replace("_",""); // tidy variable name
question.name = var_name + " - " + q_label; // set variable set label
}
- Our function is called
addVariableNameToLabel
which takes only a single argument calledquestion
. - The main internal loop code is now placed within this function and remains predominantly the same. The only change is that
questions[i]
is replaced withquestion
due to this code taking place within the function itself rather than the loop, so it instead takes its input from the function argument. - The contents of the original loop are now simply the function name and the
questions[i]
input.
Step 9: Check your code and save
- Press the Play button to check for code errors which, if any, will appear on the screen.
- If there are no errors, press OK and enter a name for the file so it can then be saved to your Displayr Cloud Drive.
- Run your script from the toolbar via Anything > [Company name] and choose the appropriate script to see if it works.
- If you don't get what you're after, go back to the QScript Editor via Anything > [Company name] > Open QScript from Displayr Cloud Drive, select your script, and re-check your code.
Here is the updated JavaScript in full:
includeWeb("QScript Selection Functions"); // load one of our packages
var user_selections = getAllUserSelections(); // identify the selected variable sets
var questions = user_selections.selected_questions; // get all the variable sets
var n_questions = questions.length; // number of variable sets
for (var i = 0; i < n_questions; i++) { // loop through the variable sets
addVariableNameToLabel(questions[i]); // run the custom function below
}
log("Your variable set labels have now been updated"); // print a message once finished
function addVariableNameToLabel(question) { // a custom function
var q_label = question.name; // get variable set label
var var_name = question.variables[0].name; // name of first variable in variable set
var_name = var_name.substring(0,3).replace("_",""); // tidy variable name
question.name = var_name + " - " + q_label; // set variable set label
}
Resources: Learning JavaScript
How to Work with Conditional JavaScript Formulas
How to Manipulate Strings Using JavaScript
How to Work with JavaScript Arrays and Loops
How to Work with JavaScript in Displayr
How to Troubleshoot JavaScript Code in Displayr
Series: Learning How to Write Your Own QScripts
1. How to Work With Variables via QScript
2. How to Create a Banner via QScript
3. How to Create User Input Prompts in QScripts
4. How to Create Diagnostic Messages and Perform Validations via QScript
5. How to Modify Variables and Value Attributes via QScript
6. How to Create Custom Variables via QScript
7. How to Add Pages, Folders, and Headings via QScript
8. How to Create Tables and Calculations via QScript
9. How to Create a Visualization via QScript
10. How to Modify Tables via QScript