Using Formula Scripting to Calculate an Average

A hidden formula item can be added to an eForm to calculate the average of certain values collected from the eForm questions.

Simple Averages

Generating a simple average is straightforward if you can always assume a fixed number of answered questions (i.e. if you require a response to all questions).

Simple Average = Total Value of Responses / Number of Questions
Example:

If you have five questions with refs 'q1', 'q2', 'q3', 'q4', and 'q5', your formula would look like this:

(q1.p + q2.p + q3.p + q4.p + q5.p) / 5
Copy Rule

Averages of Answered Questions

However, it gets a bit trickier if you only want to count a question when it’s answered. The main difference is that you need to calculate the number of questions that are answered for the denominator.

Average Answer = Total Value of Responses / Number of Questions Answered

You can check if a question has been answered by looking at its literal response (.r).

q1.r == ''
means the answer is blank
q1.r == 'N'
means the answer is "No"
q1.r == 'Y'
means the answer is "Yes"

The following is JavaScript shorthand for saying "use 1 if q1.r isn’t empty; otherwise use 0"

(q1.r != '' ? 1 : 0)
Copy Rule
Example:

Using the previous example, if "q3" was left blank, you would only want to divide by 4 when generating the average. That means you need to calculate the denominator by adding 1 for each answered question.

This is what your new formula would look like:

(q1.p + q2.p + q3.p + q4.p + q5.p) / ((q1.r != '' ? 1 : 0) + (q2.r != '' ? 1 : 0) + (q3.r != '' ? 1 : 0) + (q4.r != '' ? 1 : 0) + (q5.r != '' ? 1 : 0))
Copy Rule
Have more questions? Submit a request