-
Notifications
You must be signed in to change notification settings - Fork 186
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
New linter: recommend sort(x)
over x[order(x)]
#1512
Comments
If you agree this would be a good addition to the package, I could be interested in trying to submit a PR. I can't guarantee I will manage to do so though. I've read the relevant vignette, which I found useful but I'm still not completely sure how to write the XPath code. |
Please feel free to open a PR and, if you get stuck somewhere, we will be more than happy to help! Thanks a lot. |
I'm getting sidetracked by other projects so in case I forget about this, here are some test cases for safe keeping: test_that("sort_linter skips allowed usages", {
expect_lint("order(y)", NULL, sort_linter())
expect_lint("y[order(x)]", NULL, sort_linter())
# If another function is intercalated, don't fail
expect_lint("x[c(order(x))]", NULL, sort_linter())
})
test_that("sort_linter blocks simple disallowed usages", {
lint_message <- rex::rex("sort(x) is better than x[order(x)].")
expect_lint("x[order(x)]", lint_message, sort_linter())
# Works with extra args in order()
expect_lint("x[order(x, decreasing = TRUE)]", lint_message, sort_linter())
# ...even in disorder
expect_lint("x[order(decreasing = TRUE, x)]", lint_message, sort_linter())
}) |
One issue I see here is that these two options won't be equivalent in the presence of missing values: x <- c(1, 4, NA, 2, 8)
sort(x)
#> [1] 1 2 4 8
x[order(x)]
#> [1] 1 2 4 8 NA Created on 2022-09-16 with reprex v2.0.2 |
So I guess our suggestion should be to set x <- c(1, 4, NA, 2, 8)
sort(x, na.last = TRUE)
#> [1] 1 2 4 8 NA
x[order(x)]
#> [1] 1 2 4 8 NA Created on 2022-09-16 with reprex v2.0.2 WDYT? |
I think your proposal makes sense to ensure the behaviour is identical, even though I don't think it makes a lot of sense to order a vector with I'll leave some time for others to weigh in and then update the PR accordingly. |
I think it would be nice to have a linter to recommend using
sort(x)
to sort a vector instead ofx[order(x)]
:Created on 2022-08-26 by the reprex package (v2.0.1.9000)
Possible issues
sort()
andorder()
are both generic and it is theoretically possible that some packages only provide S3 methods for one of them. In this case, they could not be strictly equivalent. However, I would say it's likely a bug in the package.The text was updated successfully, but these errors were encountered: