File: sort_linter.Rd

package info (click to toggle)
r-cran-lintr 3.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 4,396 kB
  • sloc: sh: 13; xml: 10; makefile: 2
file content (82 lines) | stat: -rw-r--r-- 2,275 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/sort_linter.R
\name{sort_linter}
\alias{sort_linter}
\title{Check for common mistakes around sorting vectors}
\usage{
sort_linter()
}
\description{
This linter checks for some common mistakes when using \code{\link[=order]{order()}} or \code{\link[=sort]{sort()}}.
}
\details{
First, it requires usage of \code{sort()} over \code{.[order(.)]}.

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

Second, it requires usage of \code{\link[=is.unsorted]{is.unsorted()}} over equivalents using \code{sort()}.

The base function \code{is.unsorted()} exists to test the sortedness of a vector.
Prefer it to inefficient and less-readable equivalents like
\code{x != sort(x)}. The same goes for checking \code{x == sort(x)} -- use
\code{!is.unsorted(x)} instead.

Moreover, use of \code{x == sort(x)} can be risky because \code{\link[=sort]{sort()}} drops missing
elements by default, meaning \code{==} might end up trying to compare vectors
of differing lengths.
}
\examples{
# will produce lints
lint(
  text = "x[order(x)]",
  linters = sort_linter()
)

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

lint(
  text = "sort(x) == x",
  linters = sort_linter()
)

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

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

lint(
  text = "sort(x, decreasing = TRUE) == 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]

}
\seealso{
\link{linters} for a complete list of linters available in lintr.
}
\section{Tags}{
\link[=best_practices_linters]{best_practices}, \link[=efficiency_linters]{efficiency}, \link[=readability_linters]{readability}
}