Documentation

13A.6 Mutate, filter, and expression grammar

--mutate creates or replaces columns with R-style expressions. Assignments are sequential, so a later assignment may use a column made earlier:

--mutate "BMI = WT / (HT / 100)^2; LOGDV = ifelse(DV > 0, log(DV), NA)"

The frozen gallery uses exactly these derivations. Mutation is row-wise: it does not compute subject AUC, rolling summaries, lagged records, or other quantities requiring a complete profile.

Useful expression patterns

Arithmetic, comparisons, Boolean operators, and common functions such as log, exp, sqrt, abs, round, ifelse, is.na, paste0, and membership with %in% support typical preparation. Expressions can also appear directly where a variable is expected, such as --x "log(DV)" or --color "factor(DOSE)".

factor() forces a discrete encoding; continuous() forces a numeric gradient. These functions change plotting interpretation, not the stored input column.

Filters retain rows for which the expression is true. For a pharmacometric record dataset, --filter "EVID == 0 & DV > 0" commonly restricts plots to positive observations. Missing or invalid results do not become true. Quote the whole expression so PowerShell does not interpret operators.

Invalid mathematics

Logarithms of nonpositive values and other invalid calculations become missing rather than magically corrected values. Use ifelse to make the rule explicit and review missing counts. Unit conversions should be documented in names or labels; arithmetic does not attach units.

Common mistakes

  • Expecting grouped or profile-wise calculations from row-wise mutate.
  • Taking log(DV) without handling zero and negative values.
  • Forgetting shell quotes around &, parentheses, or comparison operators.
  • Using factor() as if it changed the source file permanently.

Checklist

  • Write units into the derivation review.
  • Test mutations with a short listing table.
  • Handle invalid domains explicitly.
  • Count rows before and after filters.
  • Use dedicated commands for longitudinal PK derivations.

Further reading

See Chapter 13's mutate grammar, data-step order, aesthetics, and limits.