Documentation

Summing Numeric Values

A common data-prep task is rolling several numeric answers into a single total. In the example healthcare survey, respondents report their monthly prescription, visit, and travel costs separately. For analysis, we want one combined out-of-pocket figure.

The recipe
from survey import Recoder

r = Recoder(**globals())

prescription_cost = r.get_value("monthly-prescription-cost") or 0
visit_cost = r.get_value("monthly-visit-cost") or 0
travel_cost = r.get_value("monthly-travel-cost") or 0

r.store_value("Total monthly healthcare cost", prescription_cost + visit_cost + travel_cost)
How it works

Each get_value call returns the respondent's answer to one numeric question. The or 0 guard matters: if a question was skipped or left blank, get_value returns None, and adding None to a number raises an error. Falling back to 0 keeps the arithmetic safe and treats a missing cost as no cost.

With the three values in hand, the sum is ordinary Python. store_value then writes the result back as a new reporting variable named "Total monthly healthcare cost", which appears alongside the original questions in your reports.

Variations

If you are summing a longer list of questions, read them in a loop and use sum so you are not repeating yourself:

cost_ids = [
    "monthly-prescription-cost",
    "monthly-visit-cost",
    "monthly-travel-cost",
]

total = sum((r.get_value(cost_id) or 0) for cost_id in cost_ids)

r.store_value("Total monthly healthcare cost", total)

Decide deliberately whether a blank should count as 0 or should exclude the respondent from the total. If a missing answer means "we don't know" rather than "zero", consider marking those respondents instead of defaulting them to zero, so the average is not pulled down by incomplete data.