Search code examples
rdplyrtidyversestringr

Order a number by increased digits


Apologize if it has been already asked but I'm trying to "change" the order of digits of numbers in a vector.

Let's take as an example this vector:

vector = c("5213456","17235896","23731074")

I'd like to have results as follows :

"1234556","12356789","01233477"   

I know it's a bit weird to ask this but I have combinations of numbers in a column of my dataframe, and I spotted some duplicated cases but cannot be filtered with a simple unique() function or something else as digits are not ordered in the same way.

Thanks a lot.


Solution

  • I'd go with this:

    stringr::str_split(vector, '') |> 
      purrr::map_chr(~ sort(.x) |> paste(collapse=''))
    [1] "1234556"  "12356789" "01233477"