DRDataRaft/ docs
GitHub ↗

H04 Agree on columns and keys

H04Data, products and quality1 step

Use your current course session. Preparation and course runner · R script ↓

H04 Agree on columns and keys

Goal: Express the expected table structure as a contract.

Prerequisites: H02 and H03.

A contract declares names, types and a key. integer means whole numbers, numeric means numerical values, and logical means TRUE/FALSE. policy_id must be unique and nonmissing. This version defaults to required columns, nonmissing values and no extra columns. None of this establishes a sensible premium.

policy_contract <- dr_contract(
  "policies.contract",
  columns = c(
    policy_id = "integer",
    premium = "numeric",
    cancelled = "logical"
  ),
  key = "policy_id"
)
policy_product <- dr_add_contract(policy_product, policy_contract)
policy_run <- dr_run(policy_product, write = FALSE)
policy_rows <- dr_collect(policy_run)
print(policy_contract)
print(policy_run)

stopifnot(identical(policy_run$status, "completed"))
stopifnot(identical(policy_run$validation_status, "passed"))
stopifnot(isTRUE(all.equal(as.data.frame(policy_rows), policies)))

Expected result: Three columns, key policy_id, run status completed and validation passed. The six rows are unchanged.

Task: Would a negative premium fail this contract? Could policy_id contain a duplicate?

Show solution

A negative number is still numeric, so it needs a business rule. A duplicate key fails. Add the business rule next.

Search documentation

Search functions, packages and guides.