Q's JavaScript Library

From Q
Jump to navigation Jump to search

General purpose

Method Input Output Explanation
Q.AsNumeric(text or n) String Number Converts a text value to its corresponding number. E.g., Q.AsNumeric(" +2.4") will return the number 2.4.
Q.Label(variable) Q Variable String Converts a variable's value into its corresponding label. E.g., Q.Label(gender) may return "Female".
Q.Label(variable, dataFile) String (name of Q variable)
String (name of data file)
String A version of Q.Label for variables from other data files. Use variables from all data files must be checked. E.g., Q.Label("LastPurchase", "Sales.csv")
Q.Source(variable) Q Variable Number Returns the original source value of a variable, ignoring any recoding or Treat as Missing settings. E.g., there is an Age variable with 5 Age categories (18-24, 25-30, etc.); it has been recoded so its numeric values are the midpoints of the ages, such that category 18-24, with an original source value of 1, is recoded as 21; in JavaScript, Age would return 21, whereas Q.Source(Age) would return 1.
Q.Source(variable, dataFile) String (name of Q variable)
String (name of data file)
Number A version of Q.Source for variables from other data files. Use variables from all data files must be checked.
Q.GetValue(variable) String (name of Q variable) Number Return the value of a variable, i.e. Age and Q.GetValue("Age") are equivalent. This is only necessary in rare circumstances where the variable name conflicts with a reserved JavaScript word, such as Math, new, for, etc.
Q.GetValue(variable, dataFile) String (name of Q variable)
String (name of data file)
Number Return the value of a variable from another data file. Use variables from all data files must be checked. E.g., Q.GetValue("SalesTotal", "Sales.csv"). Single quotes within the dataFile name cannot be escaped, so use double quotes around the dataFile to avoid issues. Use Q.GetValue(variable) if it's in the default dataset.
Q.IsMissing(variable) Q Variable Boolean Returns true if the variable's current value is checked as Missing Data in the Value Attributes dialog.
Q.IsMissing(variable, dataFile) String (name of Q variable)
String (name of data file)
Boolean A version of Q.IsMissing for variables in other data files.
Q.transpose(array) Array (2D) Array (2D) Transposes the input array.
Q.removeNaNs(array) Array Array Returns a new copy of the input array with any NaN values removed.
Q.DecimalsToShow(value, number_of_decimals) Number (number to be formatted)
Number (decimal places to show)
String Returns a formatted number as a string with the specified number of decimal places and commas as the thousand separator.

Manipulation of dates and times

Method Input Output Explanation
Q.AsDate(text) String Date Converts text to a date value. The resulting date value can be used in tables when the Question Type is Date, or with the Q.YearDif() and similar JavaScript methods. The text may be in numeric "day/month/year" format, or "day/MON/year" format with the MON as the name of the month, or "daymonthyear" format (with no separating mark).
Q.AsDateUS(text or n) String Date Converts text in US date format ("month/day/year") to a date value.
Q.AsDateISO(text or n) String Date Converts text in ISO date format ("year/month/day") to a date value.
Q.EncodeDate(y, m, d) Numbers Date Creates a date value that represents the date on year, month, day.
Q.EncodeDateTime(y, m, d, hh, mm, ss, ms) Numbers Datetime Creates a date-time value that represents a point in time to the resolution of a millisecond. year, month, day, hh (hour), mm (minute), ss (second), ms (millisecond).
Q.Year(date) Date Number Returns the year component of the date. E.g., Q.Year(Q.EncodeDate(2012, 10, 18)) will return 2012.
Q.Month(date) Date Number Returns the month component of the date. E.g., Q.Month(Q.EncodeDate(2012, 10, 18)) will return 10.
Q.Day(date) Date Number Returns the day component of the date. E.g., Q.Day(Q.EncodeDate(2012, 10, 18)) will return 18.
Q.Hour(date) Datetime Number Returns the hour component of the datetime. E.g., Q.Hour(Q.EncodeDateTime(2012, 10, 18, 12, 55, 6)) will return 12.
Q.Minute(date) Datetime Number Returns the minute component of the datetime. E.g., Q.Minute(Q.EncodeDateTime(2012, 10, 18, 12, 55, 6)) will return 55.
Q.Second(date) Datetime Number Returns the second component of the datetime. E.g, Q.Second(Q.EncodeDateTime(2012, 10, 18, 12, 55, 6)) will return 6.
Q.YearDif(date1, date2) Dates Number Returns the difference between date1 and date2 in years as a whole number. E.g., Q.YearDif(Q.EncodeDate(2010, 1, 1), Q.EncodeDate(2012, 6, 15)) will return 2.
Q.MonthDif(date1, date2) Dates Number Returns the difference between date1 and date2 in months as a whole number. E.g., Q.MonthDif(Q.EncodeDate(2010, 1, 1), Q.EncodeDate(2012, 6, 15)) will return 29.
Q.WeekDif(date1, date2) Dates Number Returns the difference between date1 and date2 in weeks as a whole number. E.g., Q.WeekDif(Q.EncodeDate(2010, 1, 1), Q.EncodeDate(2012, 6, 15)) will return 128.
Q.DayDif(date1, date2) Dates Number Returns the difference between date1 and date2 in days as a whole number. E.g., Q.DayDif(Q.EncodeDate(2010, 1, 1), Q.EncodeDate(2012, 6, 15)) will return 896.
Q.HourDif(date1, date2) Datetimes Number Returns the difference between date1 and date2 in hours as a whole number. E.g., Q.HourDif(Q.EncodeDateTime(2012, 10, 17, 7, 12, 33, 0), Q.EncodeDateTime(2012, 10, 17, 11, 10, 45, 0)) will return 3.
Q.MinuteDif(date1, date2) Datetimes Number Returns the difference between date1 and date2 in minutes as a whole number. E.g., Q.MinuteDif(Q.EncodeDateTime(2012, 10, 17, 7, 12, 33, 0), Q.EncodeDateTime(2012, 10, 17, 11, 10, 45, 0)) will return 238.
Q.SecondDif(date1, date2) Datetimes Number Returns the difference between date1 and date2 in seconds as a whole number. E.g., Q.SecondDif(Q.EncodeDateTime(2012, 10, 17, 7, 12, 33, 0), Q.EncodeDateTime(2012, 10, 17, 11, 10, 45, 0)) will return 14292.

Statistical analysis

Method Input Output Explanation
Q.dNorm(x, mean, sd, NaNvalue) Numbers Number Density function of the normal distribution; NaNvalue is the value returned if the density cannot be evaluated.
Q.dMR(x, w) Array of Booleans
Array of Numbers
Number Density function of the dependent multinomial distribution.
Q.qTukey(p, df, n_groups) Numbers Number Density function for Tukey's T Range Distribution (for post hoc HSD). n_groups is the number of independent samples
Q.pTukey(q, df, n_groups) Numbers Number Cumulative density function for Tukey's T Range Distribution (for post hoc HSD). n_groups is the number of independent samples.
Q.Proportions(values) 2D Array of Numbers Array of Numbers Computes the frequency table containing proportions, where the entries in the table are the order of the unique values of the input variable.
Q.ClassifyVariables(values, instructions) Array of Numbers
2D Array of Numbers
Number For an Array of values identifies the element in another Array called instructions that has the smallest Euclidean distance from the values. E.g., when instructions contains cluster means and values contains a respondent's values, this function returns the cluster membership of a respondent. To obtain an example of this, use Cluster Analysis and edit the resulting variable in the Variables and Questions tab.
Q.pDunnett(statistic, n_control, n_comparisons) Number
Number
Array of Numbers
Number CDF of Dunnett's t-distribution. statistic is the t-statistic to be evaluated. n_control is the sample size of the control group. n_comparisons is the sample size of each of the comparison groups.
Q.linearRegression(dependent_question, independent_questions, filter_variables, weight_variable) Runs a linear regression specified by the dependent question, independent questions, filters and weight variables, and returns a LinearRegression object. The regression includes an intercept term.

dependent_question The dependent question, whose type has to be "Number".
independent_questions An array of the independent questions, whose types are "Number" or "Number - Multi".
filter_variables An array of the filter variables, null if no filter variables are to be specified.
weight_variable The weight variable, null if no weight is to be specified.
Example:
var dependent_question = project.dataFiles[0].getQuestionByName("Q3. Age in years");
var independent_question = project.dataFiles[0].getQuestionByName("Q9. Cola per week");
var filter_variable = project.dataFiles[0].getVariableByName("PreferredCola");
var lin_reg = Q.linearRegression(dependent_question,
    [independent_question], [filter_variable], null);
log(lin_reg.rSquared);
Q.linearRegressionCrosstab(dependent_question, independent_questions, crosstab_question, filter_variables, weight_variable) Creates a linear regression crosstab object. See QScript LinearRegressionCrosstab for more information.

dependent_question The dependent question, whose type has to be "Number".
independent_questions An array of the independent questions, whose types are "Number" or "Number - Multi".
crosstab_question The crosstab question, whose type has to be "Pick One", "Pick Any" or "Date".
filter_variables An array of the filter variables, null if no filter variables are to be specified.
weight_variable The weight variable, null if no weight is to be specified.

Example:
var dependent_question = project.dataFiles[0].getQuestionByName("Q3. Age in years");
var independent_question = project.dataFiles[0].getQuestionByName("Q9. Cola per week");
var crosstab_question = project.dataFiles[0].getQuestionByName("Q2. Gender");
var filter_variable = project.dataFiles[0].getVariableByName("PreferredCola");
var lin_reg_crosstab = Q.linearRegressionCrosstab(dependent_question,
    [independent_question], crosstab_question, [filter_variable], null);
log(lin_reg_crosstab.regressions[0].contributions[0]);
    // regressions[0] corresponds to the regressions for Male
Q.createTurf(input_question, filter_variables, weight_variable) Creates a TURF object specified by a Pick Any question, an array of filter variables and a weight variable. See QScript Turf for more information.

input_question A Pick Any question whose variables correspond to products in the TURF analysis.
filter_variables An array of the filter variables. Set this to null if no filter variables are to be specified.
weight_variable The weight variable. Set this to null if no weight is to be specified.

Example:
var variable_names = ['Q9_A_3', 'Q9_B_3', 'Q9_C_3', 'Q9_D_3'];
var variables = [];
for (var i = 0; i < variable_names.length; i++)
    variables.push(project.dataFiles[0].getVariableByName(variable_names[i]));
var filter_variable = project.dataFiles[0].getVariableByName("PreferredCola");
var turf = Q.createTurf(question, [filter_variable], null);

Statistical analysis

Method Explanation
Q.calculateTable(blue, brown, filters, weight, which_statistics_table) Calculate a RAW DATA table, SUMMARY table, or crosstab. This allows you to bring in data from unrelated tables into one table.

The table which is returned may be interrogated using the exact same methods and properties as the "table" which is passed into Table JavaScript.

blue The question that would be in the blue dropdown of the table.
brown The item that would be in the brown dropdown of the table. Supply either 'RAW DATA' to calculate the 'blue' question's raw data, 'SUMMARY' to calculate a summary table of the 'blue' question, or supply a question to calculate a crosstab between the 'blue' question and the 'brown' question.
filters The filters to apply to a table. Supply an array of filter variables, or an empty array for no filtering. When running in Table/Plot JavaScript you can re-use the filters that have been chosen in Q's dropdowns by giving the special string '!UseQFilters' in your array.
weight The weight to apply to a table. Supply a variable, or null for no weighting. When running in Table/Plot JavaScript you can re-use the weight chosen in Q's dropdown by giving supply the special string '!UseQWeight'.
which_statistics_table Which statistics table to return. Valid options: 'Main' (default), 'Right' (representing Statistics - Right) or 'Below' (representing Statistics - Below). If there are no Statistics - Right or Statistics - Below available for the blue/brown question combination, then an error occurs. This option was added in Q 4.11.2.

Examples:
// Alter the table's statistics so that each row (soft drink brand) is
// showing statistics filtered to respondents that prefer the brand.

// Create a map from brand name (as seen in the row labels) to the
// filter variable name which should be used to filter it.
var brands_to_filter = {
    'Coke': 'CokePreferred',
    'Diet Coke': 'DietCokePreferred',
    'Coke Zero': 'CokeZeroPreferred',
    'Pepsi': 'PepsiPreferred',
    'Diet Pepsi': 'PepsiLightPreferred',
    'Pepsi Max': 'PepsiMaxPreferred',
    'None of these': 'Indifferent'
};

// The row labels (brand names).
var brands = table.rowLabels;

// For each row (brand)...
for (var row = 0; row < table.numberRows; row++) {
    // Run this same table, filtered to preference for the brand.
    
    // Get the filter variable name for this brand.
    var brand_filter = brands_to_filter[brands[row]];
    
    // The filters we will use are the existing filters in the dropdown,
    // AND the brand filter (if any).
    var filters = ['!UseQFilters'];
    if (brand_filter)
        filters.push(project.dataFiles[0].getQuestionByName(brand_filter));
    
    // Run the table.
    var brand_table = Q.calculateTable(table.blue, table.brown, filters, '!UseQWeight');
    
    // Copy the statistics for this row (brand) from the filtered table
    // to our main table.
    var stats = table.statistics;
    for (var stat = 0; stat < stats.length; stat++) {
        // Get the values from the filtered table.
        var filtered_values = brand_table.get(stats[stat]);
        
        // Get the values from the main table.
        var main_values = table.get(stats[stat]);
        
        // Copy the values from the filtered table to the main table,
        // just for this row/brand.
        for (var column = 0; column < table.numberColumns; column++)
            main_values[row][column] = filtered_values[row][column];
            
        // Set the altered values to the main table.
        table.set(stats[stat], main_values);
    }
}


// Create "row comparisons" - the same as column comparisons, but for rows.
// Each row gets its own letter - A, B, C...
// The comparisons are shown to the right of the first statistic in each cell.

// Run a crosstab of this table with the questions transposed.
var transposed = Q.calculateTable(table.brown, table.blue, ['!UseQFilters'], '!UseQWeight');

// For each row of this table...
for (var row = 0; row < table.numberRows; row++) {
    // Get the column letter of this row in the transposed table.
    var column_letter = transposed.get('Column Names')[0][row];
    
    // Change the row label to include the 'column' letter.
    var row_labels = table.rowLabels;
    row_labels[row] = row_labels[row] + ' [' + column_letter + ']';
    table.rowLabels = row_labels;
    
    // Get the column comparisons from the transposed table.
    var column_comparisons = transposed.get('Column Comparisons');
    
    // Store the column comparisons next to the primary statistic.
    var cell_text = table.cellText;
    for (var column = 0; column < table.numberColumns; column++) {
        // Removing spaces between column letters.
        var text_without_spaces = column_comparisons[column][row].replace(/ /g,"");
        // Set the text for the cell.
        cell_text[row][column] = [' ' + text_without_spaces];
    }
    table.cellText = cell_text;
}
Q.htmlBuilder() Creates a HtmlBuilder (JavaScript) object, which can be used to create a HTML fragment containing paragraphs, bulleted items and tables, for input into a Text item.
Q.interpolateColor(color1, color2, proportion) Finds a color some proportion of the way between color1 and color2.

color1 a color name (e.g. 'red') - see JavaScript Color Table for a complete list, an HTML color (e.g. '#FF0000' for red), or an array of red, green, blue numbers from 0-255 (e.g. [255, 0, 0] for red).
color2 A color as above.
proportion A number, capped to be between zero and one.

Returns: A color specified as an array of [R, G, B].

Example:
Q.interpolateColor("blue", "red", 0.3);
Q.fileFormatVersion() Returns a version number for the system running this script. Note that this is not the normal Q version number because it is not available in Displayr. You can rely on this number changing when the second number in the Q version changes. (e.g. from Q5.3 -> Q5.4.) It may change for minor versions (the third number), or it may not.
Q.safeJavaScriptReferenceToVariable(variable_name) Allows JavaScript variables to safely refer to any variable name, even if it is a reserved word, or otherwise problematic.

Returns either the original <c>variable_name</c>, or (if the <c>variable_name</c> is unsafe for use in JavaScript) a fragment of code that can be used within a JavaScript variable to safely refer to that variable. Available in Q 5.10+

See also