Using if formula in calculation for multiple condition

1. What is the issue? Please be detailed.
I am trying to add a calculation to score a question based on the option selected. There are four options in the question. If respondent select the first option, the score is 5. If second option is selected, the score is 3. If the third option is selected, the score is 2 and if the last option is selected, the score is 0

2. What steps can we take to reproduce this issue?
N/A

3. What have you tried to fix the issue?
I used if formula and or statement for the calculation. For example, if(${question_1}='option1',5,0) or if(${question_1}='option2',3,0) or if(${question_1}='option3',2,0) or if(${question_1}='option4',0,0)
4. Upload any forms or screenshots you can share publicly below.
N/A

You could replace the or with + to sum the outcomes of the if statements.

Or use nested ifs (replace the 0 in the first if with the second if etc) to continue testing the selection until you get a match or exhaust options.

Or use an instance lookup to get the score from a column in the choice list.

Or, simplest, set the name value for your question choices to the score desired, if you only need the score and not the question selection value.

@ahblake Please provide an example of using nested ifs for the sample provided in my question. Thank you.

if(${question_1}='option1',5,if(${question_1}='option2',3,if(${question_1}='option3',2,if(${question_1}='option4',0,0))))

3 Likes

This is worth highlighting :+1:

1 Like

Another option might be to add a score column to the choices list and get the value with the search() function.

Do you maybe mean instance? search is an appearance that can only be used in conjunction with external CSVs and selects. We don't generally recommend it because it doesn't work with Enketo and is generally very different from other ways of building selects.

You're correct that this could be done with a score column. Then the score could be looked up using something like instance('name_of_choice_list')/root/item[name=${question_1}]/score. This says to look in the choice list named name_of_choice_list, find the item with name that matches what was selected in question_1, and then gives back its score.