How to sort column with letters and numbers ?

Hi , I want to sort this properly:
obraz

so DES2 is situated after DES1. How do I do it, please ?

You can use str_sort() from the {stringr} package.

x = c('DES1', 'DES10', 'DES11', 'DES12', 'DES2', 'DES5', 'DES33', 'DES3')

stringr::str_sort(x, numeric = T)
#> [1] "DES1"  "DES2"  "DES3"  "DES5"  "DES10" "DES11" "DES12" "DES33"

Created on 2023-02-02 with reprex v2.0.2.9000

1 Like

How to do it in pipe ? How to fix it ? It throws an error:

df %>% stringr::str_sort(.$name, numeric = T)
Error in `stringr::str_sort()`:
! `decreasing` must be `TRUE` or `FALSE`, not a character vector.

or:

df %>% stringr::str_sort(name, numeric = T)
Error in is_logical(x, n = 1) : object 'name' not found

I would introduce a new temporary factor variable to sort by.

data.frame(name = c('DES1', 'DES10', 'DES11', 'DES12', 'DES2', 'DES5', 'DES33', 'DES3')) %>%
  # introduce new factor to arrange by
  mutate(ord = factor(name, 
                      levels = str_sort(unique(name), numeric = T), 
                      ordered = T)) %>%
  arrange(ord) %>%
  select(-ord)
#>    name
#> 1  DES1
#> 2  DES2
#> 3  DES3
#> 4  DES5
#> 5 DES10
#> 6 DES11
#> 7 DES12
#> 8 DES33

Created on 2023-02-02 with reprex v2.0.2.9000

Why does it say that object name not found as this is a column in df dataframe ?

That's odd. Can you start a fresh session and try again?

I just did, when I have changed to string:

df %>% stringr::str_sort("name", numeric = T)

it says:

Error in `stringr::str_sort()`:
! `decreasing` must be `TRUE` or `FALSE`, not the string "name".

It must be a bug in R as not first time as I experience that. We are allowed to use columns's names in pipe without quotes, aren't we ?

Did you try copying and pasting the example I shared that creates a new variable ord?

Yes I did, thank you, it works. Now I try to find the reason for those errors.

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.