r-lib / lintr

Static Code Analysis for R
https://lintr.r-lib.org
Other
1.16k stars 184 forks source link

Lint `rev(sort(x))` pattern in `seq_linter()` in favour of the more efficient alternative #2614

Open IndrajeetPatil opened 2 weeks ago

IndrajeetPatil commented 2 weeks ago

As mentioned in the docs for rev():

Note that this is no longer needed (nor efficient) for obtaining vectors sorted into descending order, since that is now rather more directly achievable by sort(x, decreasing = TRUE).

x <- rnorm(1e5)

bench::mark(
  sort(x, decreasing = TRUE),
  rev(sort(x))
)[1:5]
#> # A tibble: 2 × 5
#>   expression                      min   median `itr/sec` mem_alloc
#>   <bch:expr>                 <bch:tm> <bch:tm>     <dbl> <bch:byt>
#> 1 sort(x, decreasing = TRUE)   2.16ms   2.25ms      402.    1.15MB
#> 2 rev(sort(x))                  2.4ms   2.52ms      391.    2.29MB

But, currently, we don't lint it:

library(lintr)
lint(text = "rev(sort(x))", linters = sort_linter())

Created on 2024-06-19 with reprex v2.1.0