Learn R Programming

lintr (version 3.1.0)

sort_linter: Require usage of sort() over .[order(.)]

Description

sort() is the dedicated option to sort a list or vector. It is more legible and around twice as fast as .[order(.)], with the gap in performance growing with the vector size.

Usage

sort_linter()

Arguments

Tags

best_practices, efficiency, readability

See Also

linters for a complete list of linters available in lintr.

Examples

Run this code
# will produce lints
lint(
  text = "x[order(x)]",
  linters = sort_linter()
)

lint(
  text = "x[order(x, decreasing = TRUE)]",
  linters = sort_linter()
)

# okay
lint(
  text = "x[sample(order(x))]",
  linters = sort_linter()
)

lint(
  text = "y[order(x)]",
  linters = sort_linter()
)

# If you are sorting several objects based on the order of one of them, such
# as:
x <- sample(1:26)
y <- letters
newx <- x[order(x)]
newy <- y[order(x)]
# This will be flagged by the linter. However, in this very specific case,
# it would be clearer and more efficient to run order() once and assign it
# to an object, rather than mix and match order() and sort()
index <- order(x)
newx <- x[index]
newy <- y[index]

Run the code above in your browser using DataLab