Add a data process in pre-calculate

Updated at July 31st, 2020

You can make programatic changes to your survey data by writing data processes. For small modifications, pre-calculate is a good place to start. It's suitable for changes that involve short data processing code.

Practical applications:

Pre-calculate

Go to project settings and click on the "Pre-calculate" tab.

You should see a page with one line of code: "return rows;". This is the most basic data process. Rows represent the primary source of a project's data. This line of code simply returns the data for the project.

Protobi will execute code in pre-calculate prior to loading your project. That's why pre-calculate is best for simple and short data processes that will not take too much time to load. 

Try this

This is a process that creates a pop up message. Copy the code below, put it in pre-calculate and "Save". 

var message =  "This dataset has " + rows.length + "respondents "
alert(message)

return rows;


The message will pop up each time the project is opened, or when the browser page is reloaded. 


Add up serval values on the same row

Project pre-calculate is useful for lightweight data processing. A common example is creating a new variable that sums several data columns in a survey. 

For example, let's say we want to create a variable that sums number of patients across all products for Q2.


We can put code in pre-calculate that creates a new variable Q2_sum. 

We'll need to run the code through a loop in order to calculate the new value for each respondent. JavaScript has a method for this referred to as iterating over rows. It takes code nested within the function, and loops through every respondent in the data.  

rows.forEach(function(row) {

row.Q2_sum = (+row.Q2_1) + (+row.Q2_2) + (+row.Q2_3)

});

return rows;

Note the use of + operator in front of each value

Protobi represents your data as a CSV text file, and all data in the file are represented as strings, e.g. the string "2" rather than the number 2. 

When processing data files, be aware of the difference because JavaScript adds strings and numbers differently. Adding two numbers yields a number (e.g., 2 + 2 is 4) but adding two strings yields a string (e.g., "2" + "2" is "22").

We can make sure numeric values are added as numbers and not strings by using the sign in front.


Result

The new variable has numeric values that you can bin into different ranges.

Variables created programmatically in Protobi are placed as the last item in the group "Fields".



Was this article helpful?