Category:QScript Reference

From Q
Jump to navigation Jump to search

This page describes provides an overview of the technical detail of QScript.

Refer to:


Classes

Creating scripts requires an understanding of how different bits of information are structured within Q. If you have limited programming experience you should first look at Category:JavaScript Reference#JavaScript Reference.

Things in JavaScript are referred to as objects. Within Q, there are various types of objects, such as Plots, Tables and Filters. Some of the different types of QScript objects, and their interrelationships, are shown in the diagram below.

Objects are manipulated by methods. For example, the createBanner method can be used on a DataFile object to create a new Question object. For example, the following code creates a new object called demo_banner:

var demo_banner = data_file.createBanner("Demographic banner",
                                         [[data_file.getQuestionByName("Age")],
                                          [data_file.getQuestionByName("Gender")],
                                          [data_file.getQuestionByName("Work status")]]);


QScriptClassesAndMethods.png

AnalysisCalculationGrid The calculation Grid is a spreadsheet-like grid. You can enter R code in each cell. This R code is run to determine the output for that cell. See Using R in Q for more details.

To create a Calculation Grid in QScript, use appendCalculationGrid() in the ReportGroup object you want to append the item to in your report.
AnalysisJavaScript A new-style plot. These plots show your data graphically and often allow you interact with the plot, or provide animation.
CalculationGridCell The cell that is part of a Calculation Grid.

Cells are automatically created by a Calculation Grid. You can access them using cell() in a Calculation Grid.
ComboboxControl The Combobox control (also known as a drop-down control) allows you to select from a list of values. The values that appear in the Combobox can be set in the itemList property. This is a string seperated by semicolons, e.g.: Choice One; Choice Two; Choice Three. Alternatively, the values can be set from a Calculation. This is done by setting the itemsFromROutput property to a Calculation that you want to use as the source.
DataFile Represents a single data file (e.g. .sav) loaded into your project. This is where you can find your questions and variables.
DataReduction The data reduction is the list of codes that appear as row/column headings in tables. You can perform the same operations here as you can in Q: merge, copy, hide, etc. The functions in this class take strings to specify rows or columns using their labels, but you can also specify rows/columns using numbers. For one-dimensional questions, use positive integers starting from zero. For Pick One - Multi questions, positive integers indicate columns (values) and negative integers indicate rows (variables). For Grid questions positive integers indicate rows and negative integers indicate columns. Use the JavaScript ~ operator to turn a positive number, starting at zero, negative. Do not use the minus sign. Note that this indexing is not affected by the question being transposed.
DataReductionValue Container for data related to a data reduction hidden value.
DateControl The date control allows you to select a date from a calender.
DropboxROutput Dropbox calculations are outputs generated by R, and are entered into dropboxes. See Using R in Q for more details.
HtmlBuilder HTML builder which creates a HTML fragment, which is used as input when writing to text items. The HTML fragment is constructed by appending elements such as paragraphs, bulleted lists and tables to it.
Image An image. This gets created from an image file on your hard drive, and then the image is stored within the Q project from then on.

To create an image, use appendImage() in the ReportGroup object you want to append the image to in your report.

To change the image, use setImage() on this object.
LinearRegression A linear regression that is run from either Table JavaScript or QScript by specifying dependent and independent questions (as well as optional filters and weight variables, in the case of QScripts). Please see Driver (Importance) Analysis for more information on the regression outputs listed below.
LinearRegressionCrosstab Runs multiple linear regressions with the same input dependent question, independent questions and weight, but with different filters. Each filter is the result of combining the input filters and a crosstab filter. The crosstab filters correspond to categories of the crosstab question if it is a Pick One question, or variables if it is a Pick Any question, or periods if it is a Date question. See QScript LinearRegression for more information on linear regression objects.
ListboxControl The Listbox control allows you to select from a list of values. The values that appear in the Listbox can be set in the itemList property. This is a string seperated by semicolons, e.g.: Choice One; Choice Two; Choice Three. Alternatively, the values can be set from a Calculation. This is done by setting the itemsFromROutput property to a Calculation that you want to use as the source.
Ngviz A new-style plot. These plots show your data graphically and often allow you interact with the plot, or provide animation.
Plot A plot. Shows your data graphically. Plot objects do not provide a way to control their formatting (line thickness, bar colour, etc). Instead you format your plots using templates (see applyTemplate()), which you create by hand.
Project Represents your project. To find your plots and tables, use report. To find your questions and variables, find your DataFile object (see dataFiles) and ask it.
Question A question from one of the data files in your project, corresponding to a question in Q. A question is made up of one or more variables.
ReportGroup A group in the project's Report tree, or the root of the report tree itself. Obtain the root of the report tree using project.report. Use these to add tables and plots.
ROutput Calculations are an output generated by R, and are located in the Report. See Using R in Q for more details.

To create a Calculation in QScript, use appendR() in the ReportGroup object you want to append the item to in your report.
ROutputTranslator This class provides an interface into the R Output (ProtoBuf) and allows the user to get the data, and the attributes from the R Output
Rule Represents a Rule. Rules can be applied to one or more tables or plots. See Q documentation for more information about Rules. Create new Rules using the RulesManager object. Add them to tables and plots using table.rules.add(). Change Rules by creating a new rule and using the replace() function in the RulesManager object.
Rules Allows manipulation of the Rule objects held by a Table object or Plot object.
RulesManager Allows you to create new Rule objects, or replace and reorder them. This object is always accessed via project.rules. The order of rules is fixed for the entire project, and can only be adjusted here. To determine the parameters required for rules in the functions below, use Q to build a rule and click the QScript button.
Shape A dashboard control created using INSERT > Control.
StatisticalAssumptions Allows one to obtain cell significance, cell arrow size and cell font color from input p-values using a table's or plot's statistical assumptions.
Table A table or crosstab. Assign Question objects to primary and (optionally) secondary. Can also show raw data.
TableOutput Returns the output of a table's calculations. This includes the row labels, column labels, and statistics.
Text A text item which may contain elements such as paragraphs, bulleted lists and tables. Its content is described internally by HTML, which can be read and overwritten.
TextboxControl The date control allows you to select a date from a calender.
Translations Allows you to modify the text used by Q when it generates tables and charts. e.g. Names of statistics, "NET".
Tree An tree produced by Create | Segments.
Turf Runs TURF optimization on a Pick Any question. Each variable in the Pick Any question represents survey responses to a particular alternative. TURF optimization computes the top portfolios of a given size in terms of portfolio reach, with ties broken by portfolio frequency.
TurfPortfolio A TURF portfolio which is returned as a result of a TURF analysis. See QScript Turf for more information.
ValueAttributes Values for a question or a single variable. Equivalent to the screen that appears when you click the "..." button in the Variables and Questions tab. Use question.uniqueValues to get the list of available values to use with these methods.
Variable A variable from one of your data files, as in each row in the Variables and Questions tab. Every variable has an associated Question object.
WordCloud A word cloud.

Global Variables/Functions

These can be used in any script, in addition to the usual functions provided by JavaScript.

project

Returns the Project object.

alert(message, help_page)

Shows a box containing your message.
messageWhatever you pass in here will be converted to a string.
help_pageOptional text containing a URL or a Q Wiki topic. A help button will be added to the dialog box. When clicked, the page corresponding to the text is opened in the default browser.
Example:
alert('The QScript is stopped!  Click OK to continue.');

askYesNo(message, help_page)

Presents message with Yes and No buttons.
messageText to appear in the dialog box.
help_pageOptional text containing a URL or a Q Wiki topic. A help button will be added to the dialog box. When clicked, the page corresponding to the text is opened in the default browser.
Returns:True if Yes pushed, false otherwise.
Example:
if (askYesNo('Do you like green?'))
    log('User likes green.');

assert(condition, message)

Checks that 'condition' is true. If not your script will be aborted.
conditionAn expression that evaluates to true or false.
messageA message to display.
Example:
assert(project.dataFiles[0].getVariableByName('Q3') != null);

confirm(message, help_page)

Presents message with OK and Cancel buttons.
messageText to appear in the dialog box.
help_pageOptional text containing a URL or a Q Wiki topic. A help button will be added to the dialog box. When clicked, the page corresponding to the text is opened in the default browser.
Returns:True if OK pushed, false otherwise.
Example:
if (confirm('Do you want to show an alert?'))
    alert('Alert!');

includeFile(filename)

Runs a QScript file. Any global variables or functions defined by the other script will then be available to the calling script. Duplicate calls to includeFile() with the same 'filename' are ignored.
filenameA path to a QScript source file. If the path is relative then it is relative to the directory containing the original script.
Example:
includeFile('Utilities.QScript');

includeWeb(title)

Runs a QScript file from wiki.q-researchsoftware.com. Any global variables or functions defined by the other script will then be available to the calling script. Duplicate calls to includeWeb() with the same 'title' are ignored. This may not be used in the Inputs JavaScript for a Calculation.
titleThe title of the wiki page containing the script. The page must be in the QScript Examples Library category.
Example:
includeWeb('Utilities for Selecting Variables');

log(message)

Adds a line to the output log for this script.
messageWhatever you pass in here will be converted to a string.
Example:
log('My QScript was here.');

prompt(message, default_value, help_page)

Allows the user to enter text into a single text box. If the user clicks Cancel then the script will stop running.
messageText to appear in the dialog box.
default_valuePre-entered default text for the user.
help_pageOptional text containing a URL or a Q Wiki topic. A help button will be added to the dialog box. When clicked, the page corresponding to the text is opened in the default browser.
Returns:The text that was in the edit box when the user clicked OK.
Example:
var name = prompt('Enter you name:');

scriptType()

Returns "QScript", "Rule" or "RGui" depending on how the JavaScript code is being run. See also runMode.

selectMany(message, options, help_page, initial_selected_indices)

Presents a list of alternatives, any number of which may be selected. Returns an array of indices. If the user clicks Cancel then the script will stop running.
messageText to appear in the dialog box.
optionsAn array of strings, any number of which (or none) may be selected.
help_pageOptional text containing a URL or a Q Wiki topic. A help button will be added to the dialog box. When clicked, the page corresponding to the text is opened in the default browser.
initial_selected_indicesAn optional array of indices into the options that indicates which will be selected by default.
Returns:An array of the indices chosen.
Example:
var indices = selectMany('What have you had today?', ['Breakfast', 'Lunch', 'Dinner']);
log('User has eaten '+indices.length+' meals.');

selectOne(message, alternatives, help_page, initial_selected_index)

Presents a drop-down list of alternatives. If the user clicks Cancel then the script will stop running.
messageText to appear in the dialog box.
alternativesAn array of strings, each of which is one alternative.
help_pageOptional text containing a URL or a Q Wiki topic. A help button will be added to the dialog box. When clicked, the page corresponding to the text is opened in the default browser.
initial_selected_indexOptional index into alternatives that indicates which will be selected by default.
Returns:The zero-based index of the selected alternative.
Example:
var animal_index = selectOne('What is your favourite?', ['Dog', 'Cat', 'Bird']);

See also

Category:QScript