QScript DataFile

From Q
Jump to navigation Jump to search

DataFile

Represents a single data file (e.g. .sav) loaded into your project. This is where you can find your questions and variables.

calculateVariableCountForPickAnyWithAllCombinations(selected_vars)

Calculates the total number of variables that would be created to construct new binary variables from selected variables.
selected_varsThe list of variables selected for binary variable construction
Returns:The calculated total number of variables that would be created, or -1 if overflow occurs

canTellCategoricalFromText

Whether this file type can distinguish between true user-entered text and categorical data that has been stored as text. Useful when automatically configuring a new data file.

caseIdentifiers

Controls how we remember which data rows have been modified or deleted. It may be null (default, prevents rows being modified or deleted), "case number" (which remembers rows according to their position in the data file), or a variable (whose values are used to identify modified or deleted rows).

checkExhaustiveAndExclusive(variables)

Checks whether the values of the provided variables are exhaustive and/or mutually exclusive.
variables The collection of QScriptVariable instances whose values will be evaluated.
Returns: An object-like tuple with the following properties: { exhaustive: boolean, // true if the set of variable values is exhaustive; otherwise false exclusive: boolean, // true if the set of variable values is mutually exclusive; otherwise false }

createBanner(question_name, blocks, add_sub_nets, add_overall_net, add_question_spans)

Creates a banner question, as in Q.
question_nameThe name for the new question.
blocksEach entry is an array of questions. Within each sub-array, every combination of codes will be produced. Can only be nested 2 levels deep.
add_sub_netsTrue if the NET rows of the original input questions should be retained in the banner. False to remove these NETs from the banner. The default is true.
add_overall_netTrue if a single NET row should be added to the banner that represents all of the input question categories. False to not add an overall NET row. The default is false.
add_question_spansTrue if a span of each question name should be added that spans all of the question's categories. False to not add a span for each question name. The default is true.
Returns:The new Question object.
Example:
// Creates a banner of Age, with Gender nested underneath.
f.createBanner("BANNER", [[f.getQuestionByName('Age'), f.getQuestionByName('Gender')]])
Example:
// Creates a banner of Age side-by-side with Gender.
f.createBanner("BANNER", [[f.getQuestionByName('Age')], [f.getQuestionByName('Gender')]], false, true, false)

createCategoricalVariable(name, label, vars, simple_labels, insert_before)

Creates a Pick One variable from some mutually-exclusive Pick Anys.
nameThe name of the new variable
labelThe label of the new variable, null or empty to use the label generated from value attribute labels.
varsThe variables to create from
simple_labelsFlag for using simple label for value attribute.
insert_beforeTrue to insert the new variable before the first variable in the list, false to insert after the last variable
Returns:New Pick One variable created, otherwise null

createFilterTerm(input_object, operator_string, control, values, negated)

Creates a FilterTerm object for use in filters.
input_objectThe input object (Question object or Variable object) to filter on.

Use a Question object when:

  • Filtering single-variable questions (Pick One, Number, Text, Date) - you can also use the Variable
  • Filtering Pick Any questions (multi-response binary) where you filter by which categories were selected
  • Example: Filter where Gender equals "Male" - pass the Gender question

Use a Variable object when:

  • Filtering single-variable questions (Pick One, Number, Text, Date) - you can also use the Question
  • Filtering grid/multi questions (Pick One - Multi, Number - Multi, Pick Any - Grid, Number - Grid, Pick Any - Compact, Text - Multi)
  • You need to filter on a specific variable within a multi-variable question
  • Example: Filter a specific column in a grid question - pass that column's variable
operator_stringThe operator string. Valid operators depend on the input type:
  • Pick Any questions: "Any of", "All of", "Only/exactly", "None of"
  • Categorical (Pick One questions, or categorical variables from grids): "Any of", "None of"
  • Numeric: "Equals", "Not equals", "Greater than", "Greater than or equals", "Less than", "Less than or equals"
  • Text: "Equals", "Not equals", "Contains text", "Contains word", "Starts with", "Ends with", "Regular expression"
  • Date: "Within last", "Within last period", "Equals", "Not equals", "Greater than", "Greater than or equals", "Less than", "Less than or equals"
controlOptional. The Control object that provides the filter values dynamically. Cannot be used together with values.
valuesOptional. Array of values to filter by. The type of values depends on the input:
  • Categorical single-response (Pick One): numeric category codes (e.g., [1, 2, 3])
  • Pick Any questions: Variable objects representing selected categories
  • Numeric: numbers (e.g., [18], [100.5])
  • Text: strings (e.g., ["Yes", "Maybe"])
Cannot be used together with control.
negatedWhether the filter should be negated (NOT logic). Pass true to negate, false for no negation.
Returns:A new FilterTerm object.
Example:
// Filter a Pick One question by specific category codes:
var gender_q = data_file.getQuestionByName("Gender");
var males_only = data_file.createFilterTerm(gender_q, "Any of", null, [1], false);  // 1 = Male

// Filter a Pick Any question by specific variables (e.g., respondents who selected specific brands):
var brands_q = data_file.getQuestionByName("BrandsUsed");  // Pick Any
var brand_a = brands_q.variables[0];  // First brand variable
var brand_b = brands_q.variables[1];  // Second brand variable
var selected_brands = data_file.createFilterTerm(brands_q, "Any of", null, [brand_a, brand_b], false);

// Filter a numeric variable by range:
var age_var = data_file.getVariableByName("Age");
var adults = data_file.createFilterTerm(age_var, "Greater than or equals", null, [18], false);

// Filter text responses containing a keyword:
var comments_q = data_file.getQuestionByName("Comments");
var positive = data_file.createFilterTerm(comments_q, "Contains text", null, ["great", "excellent"], false);

// Use negation to exclude values:
var exclude_na = data_file.createFilterTerm(gender_q, "Any of", null, [99], true);  // Exclude code 99

// Use a Control for dynamic filtering (values come from a dropdown/combobox):
var filter_control = project.report.getControlByName("GenderSelector");
var dynamic_filter = data_file.createFilterTerm(gender_q, "Any of", filter_control, null, false);

createLogicalAnd(children, negated)

Creates a LogicalAnd object that combines multiple filter conditions. All child conditions must be true for the AND node to evaluate to true. This is used to build complex filter trees for newFilterQuestion.
childrenArray of FilterTerm objects, LogicalAnd objects, or LogicalOr objects to combine with AND logic. All conditions must be satisfied for a respondent to pass the filter.
negatedIf true, negates the entire AND result (equivalent to NOT(condition1 AND condition2 AND ...)). Pass false for no negation.
Returns:A LogicalAnd object that can be used in newFilterQuestion or nested within other logical nodes.
Example:
// Create a filter for adults (18+) who are employed
var age_q = data_file.getQuestionByName("Age");
var employment_q = data_file.getQuestionByName("EmploymentStatus");

var is_adult = data_file.createFilterTerm(age_q, "Greater than or equals", null, [18], false);
var is_employed = data_file.createFilterTerm(employment_q, "Any of", null, [1], false); // 1 = Employed

// Both conditions must be true (no negation)
var adults_employed = data_file.createLogicalAnd([is_adult, is_employed], false);
var filter_q = data_file.newFilterQuestion(adults_employed, null, null, "Adults who are employed", null);

createLogicalOr(children, negated)

Creates a LogicalOr object that combines multiple filter conditions. At least one child condition must be true for the OR node to evaluate to true. This is used to build complex filter trees for newFilterQuestion.
childrenArray of FilterTerm objects, LogicalAnd objects, or LogicalOr objects to combine with OR logic. At least one condition must be satisfied for a respondent to pass the filter.
negatedIf true, negates the entire OR result (equivalent to NOT(condition1 OR condition2 OR ...)). Pass false for no negation.
Returns:A LogicalOr object that can be used in newFilterQuestion or nested within other logical nodes.
Example:
// Create a filter for respondents who are either young (18-34) OR seniors (65+)
var age_q = data_file.getQuestionByName("Age");

var is_young_min = data_file.createFilterTerm(age_q, "Greater than or equals", null, [18], false);
var is_young_max = data_file.createFilterTerm(age_q, "Less than or equals", null, [34], false);
var is_senior = data_file.createFilterTerm(age_q, "Greater than or equals", null, [65], false);

var is_young = data_file.createLogicalAnd([is_young_min, is_young_max], false);

// Either young OR senior (no negation)
var young_or_senior = data_file.createLogicalOr([is_young, is_senior], false);
var filter_q = data_file.newFilterQuestion(young_or_senior, null, null, "Young or Senior", null);

createPickAnyWithAllCombinations(selected_vars)

Creates binary variables for all combinations of categories from selected variables.
selected_varsThe variables to create from
Returns:A question contains new created binary variables.

createReportSummary(profile_questions, layout, create_results_summary, insert_after)

Creates a summary report for the data file
profile_questionsQuestions to examine in detail, if null a short report will be generated
layoutThe slide layout for the report, supported layouts are "OneTable", "OneChart", "OneTableWithText", "OneChartWithText", "TwoCharts", "TwoTables"
create_results_summaryWhether to create a results summary page, default is false
insert_afterWhere to insert the report, default is to insert the report after the first page
Returns:The first page of the report
Example:
project.dataFiles[0].createReportSummary(null, "OneChartWithText", true, null)

deleteCases(caseIds)

Deletes multiple cases based on their case identifier.
caseIdsA list of case identifiers.

deleteVariables(variables)

Deletes multiple variables. Variables must belong to the same Data Set
variablesA list of variables to be deleted

equals(obj)

Whether two objects are the same.
objThe object to compare against.
Returns:true or false
Example:
data_file.getQuestionByName('Q2').equals(data_file.questions()[0])

fileName

Get the data file's name, including an extension.

fileType

Returns SPSS, Triple-S, CSV, IBM SPSS Data Model or SQL, depending on the type of data.

getQuestionByName(name)

Finds a question using its name.
nameQuestion name. Must be matched exactly. e.g. 'Age'
Returns:A Question object, or null if there is no such question.

getQuestionsByName(partial_name)

Finds all questions with a particular name, or part of a name.
partial_nameThe text we are looking for. The match is not case sensitive.
Returns:An array of Question objects. As always, the array begins at [0].
Example:
file.getQuestionsByName("Demographic:");

getVariableByName(name)

Finds a variable using its name.
nameVariable name (not label). e.g. 'Q1'. Must be matched exactly.
Returns:A Variable object, or null if there is no such variable.

getVariablesByName(partial_name)

Finds all variables matching 'partial_name'.
partial_nameWe look for variables with that string anywhere in their names. The match is not case sensitive.
Returns:An array of Variable objects. As always, the array begins at [0].
Example:
file.getVariablesByName("Q1_")

id

Returns the unique internal id of the data file. This remains the same even if the data file is updated with a new name.

moveAfter(to_move, after)

Moves around variables in the list of variables and questions. Variables in a single question will always be kept together, but they will be reordered if necessary.
to_moveThe variables to move. This should be an array of Variable objects.
afterThe variable after which it will be placed. null to move it to the start of the list.
Example:
dataFile.moveAfter(q3.variables, gender);

name

Gets/sets the name used to refer to this data file. Normally this will be the filename of the data file, including its extension, but not including the directory.

net(variables)

Determines if the net constructed would be 100%.
variablesAn array of Variable object, all from this data file.
Returns:True if the NET constructed would be 100%.

newFilterQuestion(root, question_name, variable_name, variable_label, after)

Create a new Question object using FilterTerm objects, LogicalAnd objects, and LogicalOr objects. This creates a filter question (also known as a Binary Variable) that can be applied to outputs to include/exclude respondents based on conditions.
rootThe root node of a filter tree. This can be:
  • A single FilterTerm object (created with createFilterTerm)
  • A LogicalAnd object combining multiple conditions with AND logic (created with createLogicalAnd)
  • A LogicalOr object combining multiple conditions with OR logic (created with createLogicalOr)
  • Nested combinations of the above for complex filtering logic
question_nameOptional. The name of the new filter question. Pass null to auto-generate. Must be a valid question name if provided.
variable_nameOptional. The name of the new binary variable. Pass null to auto-generate. Must be a valid variable name if provided.
variable_labelOptional. The label/description for the filter. Pass null to auto-generate from the filter conditions.
afterOptional. The Variable object after which this new filter question will be inserted. Pass null to insert at the top of the data file.
Returns:The new Question object, which can be applied to outputs or used in further analysis.
Example:
// Example 1: Simple filter with AND logic (respondents aged 18-34 who are interested)
var age_q = data_file.getQuestionByName("Age");
var interest_q = data_file.getQuestionByName("Interested");

var age_min = data_file.createFilterTerm(age_q, "Greater than or equals", null, [18], false);
var age_max = data_file.createFilterTerm(age_q, "Less than or equals", null, [34], false);
var interested = data_file.createFilterTerm(interest_q, "Any of", null, [1], false); // 1 = "Yes"

// Combine with AND logic (all conditions must be true)
var and_filter = data_file.createLogicalAnd([age_min, age_max, interested], false);
var filter_q = data_file.newFilterQuestion(and_filter, "Young_Interested", "young_interested", null, null);

// Example 2: OR logic filter (respondents who are young OR interested)
var or_filter = data_file.createLogicalOr([age_min, interested], false);
var filter_q2 = data_file.newFilterQuestion(or_filter, null, null, "Young or Interested", null);

// Example 3: Complex nested logic - (Age 18-34 AND Interested) OR (Age 65+)
var age_senior = data_file.createFilterTerm(age_q, "Greater than or equals", null, [65], false);
var young_and_interested = data_file.createLogicalAnd([age_min, age_max, interested], false);
var complex_filter = data_file.createLogicalOr([young_and_interested, age_senior], false);
var filter_q3 = data_file.newFilterQuestion(complex_filter, null, null, null, null);

// Example 4: Multi-response question - filtering on a specific variable from a grid
var grid_q = data_file.getQuestionByName("SatisfactionGrid"); // Pick One - Multi
var service_var = grid_q.variables[0]; // "Service Quality" column
var service_satisfied = data_file.createFilterTerm(service_var, "Any of", null, [4, 5], false); // Codes 4,5 = satisfied
var filter_q4 = data_file.newFilterQuestion(service_satisfied, null, null, "Satisfied with Service", null);

newJavaScriptVariable(source_code, is_text, name, label, after, options)

Create a new JavaScript variable, as in Q. Get your variable code right in Q before trying it here.
source_codeA fragment of JavaScript. Use \n to separate lines.
is_textWhether the output is a text variable (true or false).
nameThe name of the new variable.
labelThe label of the new variable.
afterThe variable after which this new variable will be placed. Use null to put the variable at the top of your file.
optionsOptional. Pass a JavaScript object with any of the following: skipValidation True to skip validation of your JavaScript code. This makes creation of variables much faster, but there is a risk that your new variable will not work. The default is false, so validation is normally performed. accessAllRows See the 'Access all data rows' checkbox in Q. Defaults to false. accelerate See the 'Accelerate (skip logic checks)' checkbox in Q. Defaults to true if the given JavaScript is safe to accelerate. useAllDataFiles See the 'Use variables from all data files' checkbox in Q. Defaults to false.
Returns:The new Variable object.
Example:
var v = data_file.newJavaScriptVariable("Q1 == 1 ? 0.5 : 1.5", false, "weight", "Weight", null, {skipValidation:true,accelerate:true});

newLogicVariable(source_code, name, label, after)

Create a new Logic variable, as in Q. Get your variable code right in Q before trying it here.
source_codeA fragment of Logic.
nameThe name of the new variable.
labelThe label of the new variable.
afterThe variable after which this new variable will be placed. Use null to put the variable at the top of your file.
Returns:The new Variable object.
Example:
var v = data_file.newLogicVariable("LikesCoke OR Gender = [Male]", "weight", "Weight", null);

newRQuestion(source_code, question_name, variable_base_name, after, gui_control_code, gui_control_values, max_execution_minutes)

Create a new R question, as in Q. Get your R code right in Q before trying it here.
source_codeA fragment of R code. Use \n to separate lines.
question_nameThe name of the new question (must also be a suitable variable name).
variable_base_nameFor single variable questions, this is the variable name. For multi-variable questions, the variable name is the base name with an integer suffix to indicate the order of the variable in the question.
afterThe variable after which this new question will be placed. Use null to put the question at the top of your file.
gui_control_codeA fragment of Javascript code to generate GUI controls in the object inspector when this question is edited.
gui_control_valuesA JavaScript object to set values for GUI controls. It should be in the format {control_name: control_value}.
max_execution_minutesIf set, overrides the default maximum R execution time (in minutes).
Returns:The new Question object.
Example:
var q = data_file.newRQuestion("as.numeric(Q3)+10*as.numeric(Q2)", "question 1", "Q1", null);

newRVariable(source_code, variable_name, variable_label, after, gui_control_code, gui_control_values, max_execution_minutes)

Create a new R variable, as in Q. Get your R code right in Q before trying it here.
source_codeA fragment of R code. Use \n to separate lines.
variable_nameThe name of the new variable
variable_labelThe label of the new variable
afterThe variable after which this new variable will be placed. Use null to put the variable at the top of your file.
gui_control_codeA fragment of Javascript code to generate GUI controls in the object inspector when this variable is edited.
gui_control_valuesA JavaScript object to set values for GUI controls. It should be in the format {control_name: control_value}.
max_execution_minutesIf set, overrides the default maximum R execution time (in minutes).
Returns:The new Variable object.
Example:
var q = data_file.newRVariable("as.numeric(Q3)+10*as.numeric(Q2)", "rvar", null, null);
// or if you want to give it a dropbox with multiple input guids:
let js_code = "form.dropBox({name: 'formInputs', label: 'Inputs', multi: true, types: ['Variable']});";
let multiple_control_values = { 'formInputs': guids.join(";") };
let multi_input_q = data_file.newRVariable("rowSums(QDataFrame(formInputs))", "my_var", "label", null, js_code, multiple_control_values);

publishToDisplayrDriveFileName

When non-null, this tells Displayr to write out this data set to Displayr Drive whenever the document is published (usually using Export). The value of this field will be used as the name of the file in Displayr Drive, and will overwrite any existing file with that name.

questions

Gets an array containing all Question objects in this data file. The first question is [0].
Example:
project.dataFiles[0].questions.forEach(function(q) {
    if (q.isHidden)
        log(q.name + ' is hidden');
});

remove()

Removes a data file from a project. Once you have called this method you will not be able to use this DataFile object again.

saveAsSPSSOrCSVFile(path, is_unicode, use_labels)

Exports the data that Q uses for analysis as an SPSS .sav file or .csv file, where the file type is determined by the file name extension supplied in path. Files with other extensions will be saved in CSV format. All modifications done in Q will be saved (e.g. only recoded values will be saved, changed labels will be saved instead of the originals, etc.).
pathA string specifying the path of the file. You will need to double any back slashes. e.g. 'c:\\Users\\bob\\Cola.sav'
is_unicodeOptional. If true, SPSS files will be in Unicode, which is supported by modern SPSS versions. True by default.
use_labelsOptional. If true, the data will be exported with labels instead of the values. False by default.

setQuestion(new_name, question_type, variables)

Combines the variables into a single question. The variables will be removed from any questions they are already part of. Afterwards the variables will be together and in the order supplied, in the place of the first variable.
new_nameThe name for the new question.
question_typeThe type of the new question. This can be one of 'Text', 'Number', 'Pick One', 'Text - Multi', 'Number - Multi', 'Pick Any', 'Pick One - Multi', 'Pick Any - Compact', 'Pick Any - Grid', 'Number - Grid', 'Experiment', 'Ranking', 'Date' (date/time).
variablesAn array of Variables, all from this data file.
Returns:The new Question object.

totalN

Returns the number of cases in this data. This count does not include cases that have been deleted.

type

Returns 'DataFile'.

undeleteAllCases()

Undeletes all deleted cases.

variables

Gets an array containing all Variable objects in this data file. The first variable is [0].
Example:
project.dataFiles[0].variables.forEach(function(v) {
    log(v.name + ': ' + v.label);
});