-
Notifications
You must be signed in to change notification settings - Fork 127
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
Feature request: reorder factor levels using a user-supplied sorting function #117
Comments
I think a better, more general solution would be a function to sort the levels according to a user-defined sort function. Here’s an implementation suggestion: library(forcats)
fct_sort = function(.f, .fun = sort) {
f = forcats:::check_factor(.f) # Not needed in dev version
fct_relevel(f, .fun(levels(f)))
}
x = c("chr1", "chr11", "chr10", "chr2")
fct_sort(x)
#> [1] chr1 chr11 chr10 chr2
#> Levels: chr1 chr10 chr11 chr2
fct_sort(x, gtools::mixedsort)
#> [1] chr1 chr11 chr10 chr2
#> Levels: chr1 chr2 chr10 chr11 And perhaps support for a custom order function (e.g. |
FYI, |
I agree with @huftis that a more general |
Cool. Would you like me to work on a PR? (I'd forgotten I opened this issue) |
Sure! |
`fct_sort` takes a factor or character-vector (implictly converted to factor) and reorders the `levels` of that factor using a user-specified function `.fun`. Code added to `R/sort.R`, unit tests into `tests/testthat/test-fct_sort.R`. An example showing how to use `fct_sort` to sort number-containing character `levels` by the contained number.
Hi,
I was wondering whether you might consider adding a function to
forcats
that sets up factor levels according to a numerically-aware string-sorting method like gtools::mixedsort.There's a number of use cases: eg, when you end up with genomes ordered like "chr1", "chr10", "chr11" ... "chr2" rather than "chr1", "chr2", ..., in a plot if you don't hack your factors correctly
eg,
The text was updated successfully, but these errors were encountered: