Setting Up and Analyzing a Project

From Q
Jump to navigation Jump to search

This script sets up a project and combines many of the ideas from other examples in this library. It:

  • Imports some data.
  • Recodes data.
  • Changes variable type.
  • Illustrates the creation of logs.
  • Creates and edits some plots.
  • Inserts an image.
  • Creates some tables.

Please note:

  • If you run this script, whatever you are doing in Q will be closed and not saved.
  • The actual output of this script is ugly. It is designed to illustrate technical aspects of using scripts and is not intended as a template for excellence in reporting.
// In this script we set up Phone.sav, and try to use many QScript functions.
log('Starting script');
project.newProject();
var data_file = project.addDataFile(".\\phone.sav", "phone.sav", { auto_tidy_labels: true,
                                                                   auto_detect_questions: false,
                                                                   strip_labels_html: true });
alert('Configuring data file ' + data_file.fileName);
var first = data_file.variables[0];
log('First variable is '+first.name+' ('+first.question.questionType+', '+first.variableType+')')
assert(first.equals(data_file.getVariableByName('id')), 'Expected id as first question')

// Hide the respondent ID variable.  Not useful in analysis.
var report = project.report;
data_file.getVariableByName('id').question.isHidden = true;

// Fake a weight variable.
var gender_var_name = data_file.getQuestionsByName("Gender")[0].variables[0].name;
var weight = data_file.newJavaScriptVariable(gender_var_name + " == 1 ? 0.5 : 1.5", false, "weight", "Weight", null);
weight.question.isWeight = true;

// Join variables together to make a Pick Any question.
var q5_vars = data_file.getVariablesByName("Q5_")
log(q5_vars.length + ' variables match "Q5_"');
data_file.setQuestion('Q5', 'Pick Any', q5_vars);

// Treat 'Don't know' in Age as missing data, if not already.
var age = data_file.getQuestionByName('Age');
var dont_know = age.valueAttributes.getSourceValueByLabel("Don't know");
if (!age.valueAttributes.getIsMissingData(dont_know))
    age.valueAttributes.setIsMissingData(dont_know, true)
    age.variables[0].label = "Age (known)";  // Also renames question, because is just one variable.

// Create a banner, simplifying the data reduction of
// its consitituent questions first.
var gender = data_file.getQuestionByName('Gender');
var banner_gender = gender.duplicate("Gender for BANNER");
banner_gender.dataReduction.hide("NET");
banner_gender.dataReduction.moveAfter("male", "female");
var age_var = data_file.getVariableByName('q4');
var banner_age_var = age_var.duplicate();
banner_age_var.name = "ageBanner";
var banner_age = banner_age_var.question;
banner_age.name = "Age for BANNER";
banner_age.dataReduction.hide("15 and under");
banner_age.dataReduction.hide("NET");
banner_age.dataReduction.merge(["20-24 yrs", "25-29 yrs"], "20-29 yrs");
banner_age.dataReduction.merge(["30-34 yrs", "35-44 yrs"], "30-44 yrs");
banner_age.dataReduction.merge(["45-54 yrs", "55-64 yrs"], "45-64 yrs");
banner_age.dataReduction.rename("65 and over", "65+ yrs");
data_file.moveAfter(banner_gender.variables, banner_age.variables[0]);
var banner = data_file.createBanner("BANNER", [[banner_age, banner_gender]]);

// Add a plot.
var plots = report.appendGroup();
plots.name = "Plots";
var plot = plots.appendPlot("Stacked column/bar plot");
plot.primary = age;
var occupation = data_file.getQuestionByName('Occupation');
occupation.valueAttributes.setIsMissingData(-9, true);
occupation.valueAttributes.setIsMissingData(0, true);
log("Changing label for '"+occupation.valueAttributes.getLabel(7)+"' to 'Labourer'");
occupation.valueAttributes.setLabel(7, "Labourer");
plot.secondary = occupation;
log("Default plot size: " + plot.size);
plot.size = [200, 100];
plot.mainStatistics = ["n"];

// Apply a template, which turns it into a line plot.
plot.applyTemplate("Line Plot.QTemplate");

// Turn gender into a banner, which is useful for filtering.
var gender_banner = data_file.createBanner("Gender banner", [[banner_gender]]);
gender_banner.isFilter = true;
plot.filters = [gender_banner.variables[0]];

// Add a Trend plot.
plot = plots.appendPlot("Trend plot");
plot.primary = age;
plot.secondary = occupation;
plot.tertiary = gender;

// Add a Grid of Bars plot with row/column statistics
plot = plots.appendPlot("Grid of bars plot");
plot.primary = age;
plot.secondary = occupation;
assert(plot.rowStatistics.length == 0, "Should be no row statistics by default.");
plot.rowStatistics = ["Average"];
plot.columnStatistics = ["Sum", "Median"];
assert(plot.columnStatistics.length == 2, "Setting columnStatistics did not work!");

// Add an Image.
var i = plots.appendImage("Q Blue Logo.png");
i.setImage("Q Blue Logo.png");

// Add some tables.
var tables = report.appendGroup();
tables.name = "Tables";

// Add a summary table.
var table = tables.appendTable();
table.primary = data_file.getQuestionByName('Marital status');
table.secondary = "SUMMARY";
log("Default statistic: " + table.cellStatistics[0]);
table.cellStatistics = ["%", "n"];
table.columnStatistics = ["Base n"];

// Add a raw data table of same.
table = tables.copyAfter(table, tables.subItems[tables.subItems.length - 1]);  // append
table.secondary = 'RAW DATA';
table.name = table.name + " raw data";

// Add a crosstab.
table = tables.appendTable();
table.primary = occupation;
table.secondary = banner;
table.weight = weight;
tables.moveAfter(table, null);

// Set up a Pick Any - Grid and put it in a table.  Reverse values
// to count, for novelty.
var q20 = data_file.setQuestion("q20", "Pick Any - Grid", data_file.getVariablesByName("q20"))
table = tables.appendTable();
table.primary = q20;
if (!q20.valueAttributes.getCountThisValue(0)) {
    q20.valueAttributes.setCountThisValue(0, true);
    q20.valueAttributes.setCountThisValue(1, false);
}
table.name = "Q20 - INVERTED!";

// Calculate an approximate average monthly bill.
var avg_bill = data_file.getVariableByName("q26");
avg_bill.valueAttributes.setIsMissingData(0, true);
avg_bill.valueAttributes.setIsMissingData(99, true);
avg_bill.valueAttributes.setValue(1, 5);    // Less that $10 a month
avg_bill.valueAttributes.setValue(2, 15);   // $10 to $19 a month
avg_bill.valueAttributes.setValue(3, 25);   // $20 to $29 a month
avg_bill.valueAttributes.setValue(4, 35);   // $30 to $39 a month
avg_bill.valueAttributes.setValue(5, 45);   // $40 to $49 a month
avg_bill.valueAttributes.setValue(6, 62.5); // $50 to $74 a month
avg_bill.valueAttributes.setValue(7, 87.5); // $75 to $99 a month
avg_bill.valueAttributes.setValue(8, 125);  // $100 to $149 a month
avg_bill.valueAttributes.setValue(9, 175);  // $150 to $199 a month
avg_bill.valueAttributes.setValue(10, 250); // $200 or more a month
avg_bill.question.questionType = "Number"
table = tables.appendTable();
table.primary = avg_bill.question;
table.secondary = age;

// Span the labels of the Age question, so an extra level of labels appears and further describes the categories.
age.dataReduction.span(['15 and under', '16-19 yrs', '20-24 yrs'], 'Less than 25');
age.dataReduction.span(['25-29 yrs', '30-34 yrs', '35-44 yrs'], '25 to 44');
age.dataReduction.span(['45-54 yrs', '55-64 yrs', '65 and over'], '45 and older');

// Make a new variable by turning a text variable into categorical, and show a
// summary.
var q14_cat = data_file.getVariableByName('q14').duplicateAs('Categorical');
table = tables.appendTable();
table.primary = q14_cat.question;

// Turn a categorical variable into numeric without duplicating it.
// Then do the same, but duplicating.  Crosstab the two.
var q15 = data_file.getVariableByName('q15');
q15.variableType = 'Numeric';
var q16_num = data_file.getVariableByName('q16').duplicateAs('Numeric');
table = tables.appendTable();
table.primary = q15.question;
table.secondary = q16_num.question;

// Log unique values from two variables.
log('q4 unique values: ' + data_file.getVariableByName('q4').uniqueValues.join(', '))
log('q14 unique values: ' + data_file.getVariableByName('q14').uniqueValues.join(', '))

log('Finished script');

See also