Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

sort

Flag sort(x)[1], which sorts the whole vector just to read one extreme — the purpose-built min(x) (or max(x) for decreasing = TRUE) finds it in a single pass and states the intent directly.

The rule fires only on the clean shape — a [1] subset of a sort call with one positional argument and at most a literal decreasing flag — and only when sort resolves to base R; a local redefinition is left alone. The fix is unsafe: sort drops NAs by default while min/max propagate them (exact equivalence would need na.rm = TRUE), and on an empty vector sort(x)[1] is NA while min(x) warns and yields Inf.

Reading one extreme off a full sort:

smallest <- sort(x)[1]
largest <- sort(x, decreasing = TRUE)[1]
warning: sort
 --> example.R:1:13
  |
1 | smallest <- sort(x)[1]
  |             ^^^^^^^^^^ `sort(x)[1]` sorts everything to read one extreme — use `min(x)`
  = help: Use `min(x)`.
warning: sort
 --> example.R:2:12
  |
2 | largest <- sort(x, decreasing = TRUE)[1]
  |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `sort(x)[1]` sorts everything to read one extreme — use `max(x)`
  = help: Use `max(x)`.