Skip to content

str_rank()? #353

@courtiol

Description

@courtiol

R base as sorting, ordering and ranking functions. Each fits a different purpose.
As far as I can see, stringr (and stringi) don't have ranking versions of their sorting and ordering functions.
One motivation could be obtaining natural sorting in dplyr:

library(dplyr, warn.conflicts = FALSE)
foo <- tibble(x = c("A100", "B3", "A1", "A2", "A10", "A11", "A100C", "AA9"))

foo %>%
  arrange(x)
#> # A tibble: 8 x 1
#>   x    
#>   <chr>
#> 1 A1   
#> 2 A10  
#> 3 A100 
#> 4 A100C
#> 5 A11  
#> 6 A2   
#> 7 AA9  
#> 8 B3

str_rank <- function(x, ...) match(x, stringr::str_sort(x, ...))

foo %>%
  arrange(str_rank(x, numeric = TRUE))
#> # A tibble: 8 x 1
#>   x    
#>   <chr>
#> 1 A1   
#> 2 A2   
#> 3 A10  
#> 4 A11  
#> 5 A100 
#> 6 A100C
#> 7 AA9  
#> 8 B3

Created on 2020-11-18 by the reprex package (v0.3.0)

Not sure this is needed in stringi since people using stringi should be capable to define, with no difficulty, a little function like the one above on the fly, but with stringr aiming at being more accessible it seems to make sense to me...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions