Caveats for Table JavaScript for important notes on how Table JavaScript affects the display of significance results.
JavaScript for a more general discussion of how the JavaScript programming language works.
User Input for Rules to find out how to write Rules that get input from the user.
Global Functions
This is an exhaustive listing of all properties and functions available when you are writing Table JavaScript and Plot JavaScript.
There are several global functions available. These do not operate on the table, but help you write JavaScript.
To operate on the table you see on the Tables/Outputs Tab, you refer to the pre-existing variables table, right_table and below_table. These are all instances of the ModifyTableOutput class, also listed below.
alert(message, help_page)
Shows a box containing your message.
message
Whatever you pass in here will be converted to a string.
help_page
Optional 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.
message
Text to appear in the dialog box.
help_page
Optional 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.
Optional 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.
filename
A 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.
title
The 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.
message
Whatever 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.
message
Text to appear in the dialog box.
default_value
Pre-entered default text for the user.
help_page
Optional 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:
varname=prompt('Enter you name:');
scriptType()
Returns "QScript", "Rule" or "RGui" depending on how the JavaScript code is being run. See also runMode.
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.
message
Text to appear in the dialog box.
options
An array of strings, any number of which (or none) may be selected.
help_page
Optional 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_indices
An optional array of indices into the options that indicates which will be selected by default.
Returns:
An array of the indices chosen.
Example:
varindices=selectMany('What have you had today?',['Breakfast','Lunch','Dinner']);log('User has eaten '+indices.length+' meals.');
Presents a drop-down list of alternatives. If the user clicks Cancel then the script will stop running.
message
Text to appear in the dialog box.
alternatives
An array of strings, each of which is one alternative.
help_page
Optional 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_index
Optional index into alternatives that indicates which will be selected by default.
Returns:
The zero-based index of the selected alternative.
Example:
varanimal_index=selectOne('What is your favourite?',['Dog','Cat','Bird']);
ModifyTableOutput
This object allows you to read and modify the output of a table calculation. There are three of these objects supplied to your Table JavaScript, under the names table, right_table and below_table. right_table and below_table will not be defined if no row or column statistics are available.
Displays a marker in the table cell, and appends a footnote to the table's footer. The 'footnote' will be appended to the end of the normal footer that Q generates.
row
The row of the cell to display the marker.
column
The column of the cell to display the marker.
footnote_marker
The marker to display in the cell, next to a statistic value.
next_to_statistic
If you want to display the 'footnote_marker' next to a specific statistic, set this to be the order of the statistic, starting at 0. For example, '1' for the second statistic, '2' for the third, etc. To simply display the marker next to the first statistic, supply a value of 'null'.
footnote
The footnote to add to the table's footer. Duplicate footnotes will be ignored.
Example:
// Display a ^ marker in any cells that are in the column// which represent our target market - people aged 18 to 29.vartarget_column_labels=['18 to 24','25 to 29'];for(vari=0;i<target_column_labels.length;i++){varcolumn=table.columnIndex(target_column_labels[i]);// Confirm that the column index was found. If not found, the index will be -1.if(column!=-1){// Yes, it was found. Now go through each row in the column,// adding the footnote marker.for(varrow=0;row<table.numberRows;row++)table.addFootNote(row,column,'^',null,'^ This is our target market');}}
Checks every cell to see if the value for a statistic is less than a limit. If so, a text marker is placed in the cell, and a footnote is added to the table's footer.
statistic
The English name of the statistic whose values should be checked.
limit
The number limit. When the statistic value for a cell is less than this number, the footnote will be added.
footnote_marker
The marker to display in the cell.
footnote
The footnote to add to the table's footer.
Example:
// When any cell has a Column n of less than 20, add a marker and footnote.table.addFootNoteForCellsLessThan('Column n',20,'**','** sample size < 20');
availableStatistics
Returns a list of statistics that this table is capable of computing. You can check if a statistic is in this list to prevent errors when setting the table's statistics property.
blankCell(row, column)
Makes a cell blank; removes all statistics, text and significance arrows from view. In a plot, this hides the bar and labels that represent the table cell.
row
The row of the cell to make blank.
column
The column of the cell to make blank.
Example:
// When the sample size of a column is less than ten, make the cells in the column blank.// Get column sample sizes.varcolumn_ns=table.get('Column n');// Store the extra footnotes we generate for each blank column.varextra_footers=table.extraFooters;// Look at each cell.for(varcolumn=0;column<table.numberColumns;column++){// Get the sample size for this column (from the cell in the first row).varcolumn_n=column_ns[0][column];// If the column's sample size is less than 10, make each cell in the column blank.if(column_n<10){for(varrow=0;row<table.numberRows;row++)table.blankCell(row,column);// Also, add a footnote that explains why some columns are missing.extra_footers.push('Column "'+table.columnLabels[column]+'" is blank because less than 10 people were asked the question.');}}// Set the extra footnotes.table.extraFooters=extra_footers;
blue
Returns the name of the question in the blue dropdown.
blueQuestion
Returns the Question object selected in the blue dropdown.
brown
Returns the name of the item in the brown dropdown. Either 'RAW DATA', 'SUMMARY', or the name of a question (if a crosstab).
brownQuestion
Returns the Question object selected in the brown dropdown. It may also return the strings 'RAW DATA' or 'SUMMARY', when there is no crosstab.
cellArrows
Gets/sets the arrow direction and size for each cell in the table. The arrow is only shown when the cell's cellSignificance flag is true and Show significance is set to Arrows.
The number 0 indicates no arrow. A positive number indicates an upward arrow, and a negative number a downward arrow.
The number is a proportion (between 0 and 1), that is used in comparison with the cell's font to determine how large the arrow should be: 1 for a full sized arrow, and 0.1 for a tiny arrow (where the arrow head will be visible with a tiny stalk).
The initial arrow size is generated by Q according to the project's Statistical Assumptions settings, and the arrow direction according to whether the Z Statistic for the cell is positive or negative.
Example:
// Change all arrows to full height, so their size does not vary by p value.// This makes them easier to see without glasses.table.requireNumericTable();vararrows=table.cellArrows;table.rowIndices(true).forEach(function(row){table.columnIndices(true).forEach(function(column){if(arrows[row][column]>0)arrows[row][column]=1;elseif(arrows[row][column]<0)arrows[row][column]=-1;});});table.cellArrows=arrows;
cellColors
Gets/sets the background colors for each cell of the table, as an array.
The color values may either be null (no color) or a color as specified in the JavaScript Color Table.
Example:
// Color each cell that represents our client's brand in red.varcoke_row=table.rowIndex('Coca Cola');if(coke_row!=-1){// There is a Coca Cola row here!// Fetch the array of cell colors (one entry for each cell).varcolors=table.cellColors;// For all cells on this row, set the color.for(varcolumn=0;column<table.numberColumns;column++)colors[coke_row][column]='OrangeRed';// Store array of cell colors we just modified.table.cellColors=colors;}
Example:
// Color yellow any cell that a p-value of less than 5%.// Get p-values array.varps=table.get('p');// Get the cell colors array.varcolors=table.cellColors;// Look at each cell...for(varrow=0;row<table.numberRows;row++)for(varcolumn=0;column<table.numberColumns;column++){// Get the cell's p-value.varp=ps[row][column];// If the value is less than 5%, color this cell yellow.if(p<0.05)colors[row][column]='yellow';}// Store the modified cell colors.table.cellColors=colors;
Example:
// Turn the table into a "heat map", which represents the// scale of values by color - low values are blue (cold)// and high values are red (hot).//// The first statistic on the table is used for the scale of values.// // To test this example, open the Cola.Q example project and// add the example to any table.// Get the name of the first statistic.varfirst_statistic=table.statistics[0];// Get the first statistic's values.varvalues=table.get(first_statistic);// Some cells should be ignored.varignore_rows=[];varignore_columns=[];if(first_statistic=='Column %')ignore_rows.push(table.rowIndex('NET'));elseif(first_statistic=='Row %')ignore_columns.push(table.columnIndex('NET'));// Calculate the minimum and maximum values.varmin,max;for(varrow=0;row<table.numberRows;row++)for(varcolumn=0;column<table.numberColumns;column++)if(ignore_rows.indexOf(row)==-1&&ignore_columns.indexOf(column)==-1){varvalue=values[row][column];if(min==null&&max==null){min=value;max=value;}else{min=Math.min(min,value);max=Math.max(max,value);}}// Get the array of cell colors (currently blank, or white).varcell_colors=table.cellColors;for(varrow=0;row<table.numberRows;row++)for(varcolumn=0;column<table.numberColumns;column++)if(ignore_rows.indexOf(row)==-1&&ignore_columns.indexOf(column)==-1){varvalue=values[row][column];// Get the current value as a scale proportion (0-1)varscale=(value-min)/(max-min);// Make sure the current value is not missing data or infinity,// which could arise if there is insufficient data on the table...if(!isNaN(scale)&&isFinite(scale)){// Create a color to represent where this value fits on the scale.// covertHSVtoRGB() is a built-in function that Q provides.// This varies the scale by saturation instead of hue:varcolor=convertHSVtoRGB(32,scale,1);// Try and experiment using some different color schemes.// In this scheme,// the lowest color has a hue of 240 (blue).// the highest color has hue of 0 (red).// The beauty of the Hue, Saturation, Value (or Brightness) color space// means that changing the value of Hue proportionally makes the color// look 'hotter'.//var color = convertHSVtoRGB(240 * (1 - scale), 1, 1);// Set the color for this cell.cell_colors[row][column]=color;}}// Set the array of cell colors we just modified.table.cellColors=cell_colors;
cellFontColors
Gets/sets the font color for each cell in the table.
The font color is only used when the cell's cellSignificance flag is true and Show significance is set to Font Color.
The initial colours are generated by Q according to the project's Statistical Assumptions settings.
Example:
// Cells that belong to our brand of interest, Coke,// will have green/brown text instead of the default blue/red.table.requireNumericTable();varbrand='Coke';varpositive_color='limegreen';varnegative_color='brown'varfont_colors=table.cellFontColors;varsignificant=table.cellSignificance;varzstatistic=table.get('z-Statistic');table.rowIndices(true).forEach(function(row){table.columnIndices(true).forEach(function(column){if(significant[row][column]&&(table.rowLabels[row].indexOf(brand)>=0||table.columnLabels[column].indexOf(brand)>=0)){if(zstatistic[row][column]>0)font_colors[row][column]=positive_color;elsefont_colors[row][column]=negative_color;}});});table.cellFontColors=font_colors;
cellSignificance
Gets/sets a significance flag for each cell in the table. Setting this flag to true allows the cellFontColors and cellArrows to be used when displaying this cell. The initial flag is generated by Q according to the project's Statistical Assumptions settings.
Example:
// Mark any column with significant cells with an asterisk (*).table.requireNumericTable();varsymbol='*';varcolumn_labels=table.columnLabels;varsignificant=table.cellSignificance;table.columnIndices(true).forEach(function(column){varany_significant=table.rowIndices(true).some(function(row){returnsignificant[row][column];});if(any_significant)column_labels[column]=column_labels[column]+symbol;});table.columnLabels=column_labels;
cellText
Gets/sets text which is displayed next to each statistic in each cell. Any text will be shown immediately to the right of the statistical values, and before the significance arrow (if any).
This is a three-dimensional array, which has a list of strings for each row and column in the table. The list of strings in each cell has an entry for the statistics shown in the cell. For example, if the table has the statistics Column % and n, each cell will have an array of length 2, where you can store text to display next to Column % values (at index 0), and n values (at index 1).
Example:
// Display an exclamation point next to the first statistic in each cell, if it is over 80.// Get the values for the first statistic shown on the table.varvalues=table.get(table.statistics[0]);// Get the default text in each cell in the table.varcell_texts=table.cellText;// Loop through each cell...for(varrow=0;row<table.numberRows;row++)for(varcolumn=0;column<table.numberColumns;column++){varvalue=values[row][column];if(value>80){// Put an exclamation point next to the first statistic.cell_texts[row][column]=['!'];}}// Now store the new cell texts.table.cellText=cell_texts;
Example:
// Show column comparisons to the right of the first statistic's values.varfirst_stat=table.statistics[0];// If the first value in each cell is the column comparisons already// then nothing to do here.if(first_stat!='Column Comparisons'){// Try to get the column comparisons.varcolumn_comparisons=table.get('Column Comparisons');// Get the default text in each cell in the table.varcell_texts=table.cellText;// Loop through each cell...for(varrow=0;row<table.numberRows;row++)for(varcolumn=0;column<table.numberColumns;column++){// Set the cell text to be the column comparison value for this cell,// with a space before it.varcomparison_text=column_comparisons[row][column];// Removing spaces.vartext_without_spaces=comparison_text.replace(/ /g,"");// Inserting into cell.cell_texts[row][column]=[' '+text_without_spaces];}// Now store the new cell texts.table.cellText=cell_texts;}
clearColumnSpans()
Removes all column spans. Spans are an extra level of labels that can cover multiple columns.
clearRowSpans()
Removes all row spans. Spans are an extra level of labels that can cover multiple rows.
columnIndex(label)
Returns the index of 'label' in the column labels, or -1 if the 'label' cannot be found. The first column has an index of 0. This cannot be used for one-dimensional tables, because the 'statistics' are shown in columns.
label
The column label to look for.
columnIndices(include_nets_sums)
Returns the numeric indices of the columns in this table. Use these to iterate over all the columns in a table.
Gets/sets the column heading labels shown for this crosstab. This is not available for one-dimensional tables, because the statistics names are shown as columns for these. You may modify the label text and then set the array. This cannot be used for re-ordering columns; use moveColumnAfter() for that purpose. This cannot be used for adding columns; use insertColumnAfter() for that purpose.
Example:
// Add three asterisks next to the Coke category,// to bring it to the attention of the client.// Get the existing column labels.varcolumn_labels=table.columnLabels;// For each column...for(varcolumn=0;column<table.numberColumns;column++)// If the label is "Coca Cola"...if(column_labels[column]=='Coca Cola')// ... add (+=) three asteriskscolumn_labels[column]+='***';// Use our modified labels as the new column labels.table.columnLabels=column_labels;
Example:
// Under the standard column labels, add:// * Column name (A, B, C...)// * Column n// Get the column names and column n valuesvarcolumn_names=table.get('Column Names');varcolumn_ns=table.get('Column n');// Get the standard column labels.varcolumn_labels=table.columnLabels;// For each column...for(varcolumn=0;column<table.numberColumns;column++){// Adjust the label to include the column name and column n, on new lines.// '\r\n' is a special carriage-return code.column_labels[column]=column_labels[column]+'\r\n'+column_names[0][column]+'\r\n'+'n = '+column_ns[0][column];}// Set the adjusted column labels.table.columnLabels=column_labels;
columnSpans
Returns the list of labels that span the normal column labels. Each entry in the list is an object with two properties: "indices", which is a list of column indices, and "label", which is the label that spans the column. For example, if table has two column spans, one called "Sugary" that spans its first three columns, and "Sugar-free" that spans its next three columns, then columnSpans will return an array with two objects: [{ indices: [0, 1, 2], label: 'Sugary' }, { indices: [3, 4, 5], label: 'Sugar-free' }]. See rowSpans for an example showing how to use a property that is closely related to columnSpans.
decimalPlaces
Returns an object that maps from statistic names to the number of decimal places to show for that statistic.
Example:
log(table.decimalPlaces['Average']);
deleteColumn(column)
Deletes a column. This removes its entry from the column labels and its statistics. This function only needs to be called from table as the corresponding column in below_table is also deleted.
column
The index of the column to delete.
Example:
table.deleteColumn(table.columnIndex('NET'));
deleteRow(row)
Deletes a row. This removes its entry from the row labels and its statistics. This function only needs to be called from table as the corresponding row in right_table is also deleted.
Gets/sets a list of extra footer entries, which will be shown underneath the table/plot when it is printed or otherwise exported (also when exported as a chart to Office). These footer entries are appended after the normal footer generated by Q.
Example:
// Inserts a footer entry which shows the smallest cell size in the table.// Get the sizes of each cell.varsizes=table.get('n');// Keep track of the smallest size.varsmallest_size;// For each cell...for(varrow=0;row<table.numberRows;row++)for(varcol=0;col<table.numberColumns;col++){if(row==0&&col==0)// If this is the first cell, store its size.smallest_size=sizes[row][col];else// Otherwise, use the smaller of the existing size or this new one.smallest_size=Math.min(smallest_size,sizes[row][col]);}// Now we have the smallest size. Create and store// the list of extra footers, with our new entry:table.extraFooters=['Smallest cell: '+smallest_size+' respondents.'];
filters
Gets the filter variables selected for the table. An empty array is returned if there are no filters selected. Note that this property is not valid for TableOutput objects that were created using calculateTable.
forPlot
Whether table is being calculated as data to be plotted.
Returns:
true if this data is being used for a plot.
Example:
if(table.forPlot)alert("This is for a plot.");
get(statistic)
Gets the 'statistic' values for every cell in the table. Returns a two-dimensional array, where the rows are in the first index and the columns in the second index. In one-dimensional SUMMARY tables, a two-dimensional array will still be returned, with only one column in the second dimension. Use the English names of statistics you see in the Q desktop program. If you request a text statistic, the values will be JavaScript String objects. Otherwise for numeric statistics the values will be JavaScript Number objects, which are double-precision 64-bit floating point numbers - the same as Q uses internally to store and compute statistics.
statistic
The English name of the statistic you want to get the values for.
Example:
// Whenever a Column N is less than 30, add an asterisk next to the column name,// and add a footnote explaining the asterisk.// Get the Column N statistics.varcolumn_ns=table.get('Column n');// Get the column labels.varcolumn_labels=table.columnLabels;// Make a list of extra footnotes.varfootnotes=table.extraFooters;// For each column...for(varcolumn=0;column<table.numberColumns;column++){// Get the column n statistic (from the cell in the first row).varcolumn_n=column_ns[0][column];if(column_n<30){// Add an extra footnote.footnotes.push('* column "'+column_labels[column]+'" has less than 30 respondents.');// Put a marker on this column's label.column_labels[column]+='*';}}// Store the adjusted column labels and footnotes.table.columnLabels=column_labels;table.extraFooters=footnotes;
getTranslation(name_en)
Gets the user-overridden text for the output string given by the English text. If it has not been overridden then the default text under the current language settings will be returned.
name_en
English text that is normally output.
Returns:
The translated text. If you have not changed this then it will be the original English text.
Example:
alert(table.getTranslation('Column n'));
hypothesisTestingEnabled
Gets/sets whether to enable the alpha button that launches hypothesis testing.
Insert a new column with the given label. This function only needs to be called from table as a corresponding new column in below_table is also inserted. The statistics for the new column will be populated with values of NaN. This does not work for one-dimensional tables, because the columns are represented by the statistics. Add a new statistic instead using 'table.statistics'.
after_column
The new column will be inserted after this column. To insert the new column at the start of the table, supply a value of 'null'.
label
The label for the new column.
insertRowAfter(after_row, label)
Insert a new row with the given label. This function only needs to be called from table as a corresponding new row in right_table is also inserted. The statistics for the new row will be populated with values of NaN.
after_row
The new row will be inserted after this row. To insert the new row at the start of the table, supply a value of 'null'.
label
The label for the new row.
Example:
// Insert an average of the existing average statistics above this row.// Insert a new row to store the numbers.table.insertRowAfter(table.numberRows-1,'Column Average');// Get the average values for each cell.varaverages=table.get('Average');// Get the not duplicate markers for each cell. This// indicates whether the cell has been copied from// another cell, such as when NETs are created.varnot_duplicates=table.get('Not Duplicate');// For each column...for(varcolumn=0;column<table.numberColumns;column++){// Keep track of the sum of averages, and the number of// non-duplicate rows so far.varsum=0;varunique_rows=0;// For each row...for(varrow=0;row<table.numberRows;row++)// If this cell is not a duplicate...if(not_duplicates[row][column]){// Add its average value to this column's sum.sum+=averages[row][column];// And increase the count of non-duplicate rows.unique_rows++;}// We now have a sum of all the averages in this column.// Compute the average.varaverage=sum/unique_rows;// Store the average in the new 'Column Average' row// we added above.averages[table.numberRows-1][column]=average;}// Use our new average values.table.set('Average',averages);
Example:
// Add two numbers together in a new row.// Find out where the two rows are.varrow_one=table.rowIndex('Coca Cola');varrow_two=table.rowIndex('Diet Coke');// Create a new row to store the new number.table.insertRowAfter(row_two,'Combined Coke');varnew_row=row_two+1;// Get the first statistic on the table.varfirst_statistic=table.statistics[0];// Get the values of the first statistic.varstatistic_values=table.get(first_statistic);// Add the two numbers together.varsum=statistic_values[row_one][0]+statistic_values[row_two][0];// Store the sum of the two numbers.statistic_values[new_row][0]=sum;// Store the new values for the first statistic.table.set(first_statistic,statistic_values);
moveColumnAfter(column, after_column)
Move a column to another position. This adjusts the column labels and all cell statistics. This function only needs to be called from table as the corresponding column in below_table is also moved. This does not work on one-dimensional tables, since the statistics are shown in the columns. To re-order those, you must instead modify 'table.statistics'.
column
The index of the column to move, starting at 0.
after_column
The 'column' will be moved into position after this column index. To move a column to the start of the table, supply 'null' here.
Example:
// Move 'Coca Cola' to be after 'Pepsi'.table.moveColumnAfter(table.columnIndex('Coca Cola'),table.columnIndex('Pepsi'));
moveRowAfter(row, after_row)
Move a row to another position. This adjusts the row labels and all cell statistics. This function only needs to be called from table as the corresponding row in right_table is also moved.
row
The index of the row to move, starting at 0.
after_row
The 'row' will be moved into position after this row index. To move a row to the start of the table, supply 'null' here.
Example:
// Move 'Coca Cola' to be after 'Pepsi'.table.moveRowAfter(table.rowIndex('Coca Cola'),table.rowIndex('Pepsi'));
netColumns
Gets/sets which columns are NETs, via an array of column indices. These NETs are used for formatting purposes (in PDF exports) and are hidden from plots by default.
netRows
Gets/sets which rows are NETs, via an array of row indices. These NETs are used for formatting purposes (in PDF exports) and are hidden from plots by default.
numberColumns
Returns the number of columns in the table. On a one-dimensional table, this will return 1, as there is 1 column worth of cell data.
numberRows
Returns the number of rows in the table.
requireNumericTable()
Call this at the top of your script to make your script ignore text tables by aborting itself.
requireOriginalCellStatistics(statistic)
Requires that the cell statistics of the table have not been modified by previous rules. If they have, this script will abort. You don't need this if your script is examining the statistic values in table, because these will already reflect changes made by previous scripts. However if your script disregards changes already made then use this call to avoid accidentally overwriting statistics set by previous rules.
statistic
The name of the statistic that is required to be unchanged. Leave this as null to require all statistics be unchanged.
Example:
table.requireOriginalCellStatistics(null);
Example:
table.requireOriginalCellStatistics('Average');
requireOriginalRowsColumns()
Requires that the rows and columns of the table have not been deleted, moved or added to by previous rules. If they have, this script will abort. This is an essential requirement if you will use calculateTable and need to assume the rows or columns are in the same positions in both tables.
Example:
table.requireOriginalRowsColumns();
rowIndex(label)
Returns the index of 'label' in the row labels, or -1 if the 'label' cannot be found. The first row has an index of 0.
label
The row label to look for.
rowIndices(include_nets_sums)
Returns the numeric indices of the rows in this table. Use these to iterate over all the rows in a table.
Gets/sets the row heading labels shown for this table. You may modify the label text and then set the array. This cannot be used for re-ordering rows; use moveRowAfter() for that purpose. This cannot be used for adding rows; use insertRowAfter() for that purpose.
Example:
// Add three asterisks next to the Coke category,// to bring it to the attention of the client.// Get the existing row labels.varrow_labels=table.rowLabels;// For each row...for(varrow=0;row<table.numberRows;row++)// If the label is "Coca Cola"...if(row_labels[row]=='Coca Cola')// ... add (+=) three asterisksrow_labels[row]+='***';// Use our modified labels as the new row labels.table.rowLabels=row_labels;
rowSpans
Returns the list of labels that span the normal row labels. Each entry in the list is an object with two properties: "indices", which is a list of row indices, and "label", which is the label that spans the rows. For example, if table has two row spans, one called "Sugary" that spans its first three rows, and "Sugar-free" that spans its next three rows, then rowSpans will return an array with two objects: [{ indices: [0, 1, 2], label: 'Sugary' }, { indices: [3, 4, 5], label: 'Sugar-free' }].
Example:
// Add a new Average row to every span, that averages// the statistics of the other rows in that span.// Get the list of spans.varspans=table.rowSpans;// Get the list of statistics on the table.varstatistics=table.statistics;// Working backwards through the list of spans...for(vari=spans.length-1;i>=0;i--){// Get the current span.varspan=spans[i];// Get the rows in this span.varrows=span.indices;// What is the last row in this span?varlast_row=rows[rows.length-1];// Add a new Average row.table.insertRowAfter(last_row,'Average');// Remember the index of the new Average row.varaverage_row=last_row+1;// For each other row in this span, sum its statistics.// For each column...for(varcolumn=0;column<table.numberColumns;column++){// For each statistic in the table...for(varstat=0;stat<statistics.length;stat++){varvalues=table.get(statistics[stat]);varsum=0;for(varj=0;j<rows.length;j++){varrow=rows[j];sum+=values[row][column];}// Store the average in the new Average row.values[average_row][column]=sum/rows.length;// Store the values of the Average row into the table.table.set(statistics[stat],values);}}}
set(statistic, array)
Sets the values for every cell in the table, for a particular statistic. Supply a two-dimensional array, where the rows are in the first index and the columns in the second index. In one-dimensional SUMMARY tables, a two-dimensional array should still be supplied, with only one column in the second dimension. Use the English names of statistics you see in the Q desktop program. If you set a text statistic, the values must be JavaScript String objects. Otherwise for numeric statistics the values must be JavaScript Number objects.
statistic
The English name of the statistic you want to replace the values of.
array
A two-dimensional array of values for the statistic.
showMissingAs(text)
Whenever a statistic has a missing value (normally because of a zero sample size), instead of showing "NaN", show the supplied text.
text
The text to show for a statistic value, instead of "NaN".
Example:
// Show a "-" instead of "NaN" for missing values.table.showMissingAs('-');
showPercentSign
Gets/sets whether to show a percentage sign next to numbers from a percent series.
Example:
table.showPercentSign=true;
sortColumns(column_indices)
Similar to sortRows(), sorts the columns according to the new indices supplied. This function only needs to be called from table as columns in below_table are also sorted correspondingly. This does not work for one-dimensional tables, because the columns represent the statistics.
column_indices
An array of column indices, where the array specifies the new location of each column. Each number is an original column index. The place in the array is the new location for the column.
sortRows(row_indices)
Sorts the rows according to the new indices supplied. This function only needs to be called from table as rows in right_table are also sorted correspondingly.
row_indices
An array of row indices, where the array specifies the new location of each row. Each number is an original row index. The place in the array is the new location for the row.
Example:
// Sort the rows by the right-most column.// Uses the first statistic in each cell as the comparison value.// Get the values of the first statistic.varfirst_statistic=table.statistics[0];varvalues=table.get(first_statistic);// Create an array of the original row numbers, which we will sort.varrow_indices=[];for(varrow=0;row<table.numberRows;row++)row_indices.push(row);varlast_column=table.numberColumns-1;// Now sort the array of row numbers by the statistical values.// This 'function' is run many times - to compare each row against another.row_indices.sort(function(row_x,row_y){// Get the values for the two rows we are comparing.varvalue_x=values[row_x][last_column];varvalue_y=values[row_y][last_column];// Sort by the difference in the values.// This sorts in ascending order (smallest value at the top).// If you wanted descending order, you could change this to:// value_y - value_xreturnvalue_x-value_y;});// NETs, SUMs, Others and Don't Knows are always at the bottom of the table.varalways_bottom_labels=['Other',"Don't know",'NET','SUM'];// For each label...for(vari=0;i<always_bottom_labels.length;i++){varlabel=always_bottom_labels[i];// Try to get its row position.varrow=table.rowIndex(label);if(row!=-1){// If it exists (has a row position)...// Find its position in the sorted row numbers.varsorted_row=row_indices.indexOf(row);// Remove it from the sorted row numbers.row_indices.splice(sorted_row,1);// Add it to the sorted row numbers, to the end.row_indices.push(row);}}// Finally, our row numbers are now sorted in the order we want.// Instruct the table to sort the rows according to the new order.table.sortRows(row_indices);
spanColumns(column_indices, label)
Span columns with a new label. This adds an extra level of labels that covers the normal column labels.
column_indices
An array of column numbers to span.
label
The label which will span over the normal column labels.
Example:
// Span the Coke brands.table.spanColumns([table.columnIndex('Coca Cola'),table.columnIndex('Diet Coke'),table.columnIndex('Coke Zero')],'Coke Brands');// Span the Pepsi brands.table.spanColumns([table.columnIndex('Pepsi Light'),table.columnIndex('Pepsi Max'),table.columnIndex('Pepsi')],'Pepsi Brands');
spanRows(row_indices, label)
Span rows with a new label. This adds an extra level of labels that covers the normal row labels.
row_indices
An array of row numbers to span.
label
The label which will span over the normal row labels.
Example:
// Span the Coke brands.table.spanRows([table.rowIndex('Coca Cola'),table.rowIndex('Diet Coke'),table.rowIndex('Coke Zero')],'Coke Brands');// Span the Pepsi brands.table.spanRows([table.rowIndex('Pepsi Light'),table.rowIndex('Pepsi Max'),table.rowIndex('Pepsi')],'Pepsi Brands');
Gets/sets the statistics shown for this table. Unknown statistics will be ignored. Use the English names of statistics you see in the Q desktop program. Because an array of statistics is returned, you may also re-order the statistics by getting the array, sorting, then setting the array. You may add extra statistics by adding elements to the array and setting it. The names of statistics in R tables which have been generated from Q/Displayr tables will be in the language of the project that created them, but will fall back to English. This property will always try to return standard English names. Non-standard statistic names will be returned as-is (e.g. on Tables generated by other R code).
Example:
// Sort the statistics that are already shown on the table,// and then add Average at the end.// Get the existing statistics on the table (selected by the context menu).varstats=table.statistics;// Sort them alphabetically.stats.sort();// Add Average.stats.push('Average');// Use our new list as the statistics.table.statistics=stats;
suppressOutput(message)
Suppresses the normal display of a table/plot and instead shows the 'message' as text. This affects both the screen display of a table/plot and the exported version of the table/plot. The script will not continue after this call.
message
The text message to display instead of the actual table/plot.
Example:
// Do not show the output if any of the questions were// answered by less than 10 respondents, because it means the filter that// was applied by the user is too restrictive.// Get the 'Base n' statistic values for each cell.varbase_ns=table.get('Base n');// The message to show instead of the real table.varmessage='The filters you have applied contain too few people.\n'+'Change the filters to see this table again.';// If any of the 'Base n' values are less than 10, suppress the// output with a message explaining why.for(varrow=0;row<table.numberRows;row++)for(varcolumn=0;column<table.numberColumns;column++)if(base_ns[row][column]<10)table.suppressOutput(message);
type
Returns the name we use to refer to this class in the documentation.
weight
Get the weight variable selected for the table. If no weight is selected then null is returned. Note that this property is not valid for TableOutput objects that were created using calculateTable.
Pages in category 'Table JavaScript and Plot JavaScript Reference'
The following 11 pages are in this category, out of 11 total.