R / CHAPTER 02

Coercion and recycling contracts

Beginner

Check type and length before applying vector arithmetic.

By the end of this chapter

  • Predict common atomic-vector types
  • Explain exact recycling
  • Reject unsupported length mismatches

The idea

An atomic R vector uses one underlying type. Combining numbers and text therefore creates a character vector rather than preserving a separate type for each element. This differs from a list. Inspect types at the boundary of a calculation, and parse text deliberately; silently accepting mixed input can move a failure far from its original cause.

Arithmetic recycles a shorter vector along a longer one. Exact recycling can be useful for a known repeated pattern, but it can also hide a length error without warning. A warning occurs for fractional recycling, not for every mismatch. If the contract requires one weight per observation, compare lengths explicitly before multiplication instead of treating the absence of a warning as validation.

R example
x <- c(2,4,6,8)
cat(x + c(10,20), sep=",")
cat("\n", typeof(c(1,"2")), "\n", sep="")
Result
12,24,16,28
character

The two offsets repeat exactly. Adding text to an atomic vector coerces the numeric entry to text.

Try it yourself

Write a weighted-total function that rejects unequal input lengths before multiplying.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

A vector has four observations but only two weights. No warning occurs. What must a one-weight-per-observation function check?