9

I am trying to order a dataframe by making use of dplyr::arrange. The issue is that the column I am trying to sort on contains both a fixed string followed by a number, as for instance generated by the dummycode below.

  dummydf<-data.frame(values=rnorm(100),sortcol=paste0("ABC",sample(1:100,100,replace=FALSE)))

By default, using dummydf %>% arrange(sortcol) would generate a df which is sorted alphanumerically (?) but this is of course not the desired result:

values sortcol
0.708081720    ABC1
0.041348322   ABC10
1.730962886  ABC100
0.423480861   ABC11
-1.545837266   ABC12
-1.345539947   ABC13
-0.078998792   ABC14
0.088712174   ABC15
0.670583024   ABC16
1.238837680   ABC17
-1.459044293   ABC18
-2.028535223   ABC19
0.779514385    ABC2
1.360509910   ABC20

In this example, I would like to sort the column as gtools::mixedsort would do, making sure ABC2 follows ABC1 and is not preceed by ABC1-19 and ABC100 mixedsort(as.character(dummydf$sortcol)) would do that trick.

Now, I am aware I could do this by using sub in my arrange argument: dummydf %>% arrange(as.numeric(sub("ABC","",sortcol))) but that is mainly because my string is something fixed (although any regex could be used to capture the last digits following any string I suppose).

I am just wondering: is there a more "elegant" and generic way to get this done with dplyr::arrange, in the same fashion as gtools::mixedsort?

Kind regards,

FM

6
  • One slightly different approach you might consider is splitting the sortcol into two columns, for example with tidyr: extract(dummydf, sortcol, c("sort1", "sort2"), "([A-Z]+)(\\d+)", convert = TRUE) %>% arrange(sort1, sort2)
    – talat
    Commented Sep 3, 2015 at 14:25
  • Just to clarify, would you be against a data.table answer?
    – Akhil Nair
    Commented Sep 3, 2015 at 14:55
  • @AkhilNair not necessarily, I would just like an elegant and generic function that does the trick. Commented Sep 3, 2015 at 15:03
  • @docendodiscimus thanks, that is an interesting way of making the function more generic! However: is there a way to make it bit more 'robust' (e.g. to deal with special characters in the column such as ABC_1 or to deal with numbers inside the column such as A1B2C3)? Commented Sep 3, 2015 at 15:09
  • What's the problem with using gtools::mixedsort?
    – Arun
    Commented Sep 3, 2015 at 15:13

5 Answers 5

10

Here's a functional solution making use of the mysterious identity order(order(x)) == rank(x).

mixedrank = function(x) order(gtools::mixedorder(x))
dummydf %>% dplyr::arrange(mixedrank(sortcol))
1
  • 1
    This is so elegant because it still allows to further arrange by the other variables. Kind of unexpected that this function is not part of gtools. You could of course simplify it to dplyr::arrange(order(gtools::mixedorder( sortcol ))) Commented Jun 22, 2022 at 11:11
8

I don't see this answer posted so I'll throw it out. You can use mixedorder with slice to arrange it.

dummydf %>% 
  slice(mixedorder(sortcol))
1
  • 1
    Nice (concise).
    – Paul
    Commented Mar 16, 2022 at 12:15
5

Using data.table

library(data.table)
dummydf = data.table(dummydf)
dummydf[gtools::mixedorder(as.character(sortcol))]

Honestly just copied your example and stuck it in as the select argument in the data.table syntax. You already did all the hard work :).

5
  • I like the answer. Although I would prefer dplyr, for reasons of code "legibility" and use of the margrittr "piping" (i.e. the %>% operator) which is how I build up most of my data wrangling code, I think this is an excelent and elegant alternative. For now, I'll upvote it but if no one can come with a dplyr alternative I'll accept it asap. Commented Sep 3, 2015 at 15:13
  • 1
    No, I agree, that's why I wanted to clarify first in the comments. I did prefer dplyr before I got to grips with data.table syntax, but I find the versatility of data.table to be invaluable now compared.
    – Akhil Nair
    Commented Sep 3, 2015 at 15:15
  • @AkhilNair May I ask why it works? I failed to understand the syntax. I could see that "sortcol" get sorted, but how does data.table know which column to look after? I didn't know similar usage in the tutorial but I likely miss it. Many thanks!
    – ccshao
    Commented Nov 30, 2020 at 13:13
  • Running gtools::mixedorder(as.character(dummydf$sortcol)) normally returns a vector of indexes - e.g., c(79, 27, 93, .... In the data.table context, the rows are then arranged by the index vector. For example, with a data.table called dt of 3 rows, if you say dt[c(3, 1, 2)], it will show the 2nd row first, 3rd row second, and 1st row third.
    – Akhil Nair
    Commented Nov 30, 2020 at 17:28
  • @AkhilNair Thanks! I have got confused with mixedsort! Now everything is clear.
    – ccshao
    Commented Dec 2, 2020 at 15:02
1

Credit to Akhil Nair for his data.table answer which is what the first code snippet derives from. If you like the data.table answer but still want magrittr piping, you can consider calculating a new column and using piping with data.table to get your output:

dummydf %>% 
  dplyr::mutate(row_lookup = gtools::mixedorder(as.character(sortcol))) %>%
  data.table::data.table() %>% 
  .[.$row_lookup]

I think it's debatable whether that helps or detracts from the readability.

If you don't want to call data.table, you can go through some extra contortions to calculate a column you can use dplyr::arrange on. Here's one example:

library(dplyr)
bind_cols(dummydf,
          dummydf %>% 
            tibble::rowid_to_column("order") %>% 
            mutate(rowname = gtools::mixedorder(as.character(sortcol))) %>% 
            arrange(rowname) %>% 
            select(order)) %>% 
arrange(order)

I think this code is more confusing to read and isn't worth those extra contortions to avoid data.table.

0

Here is a solution that will allow for sorting if there are repeats and multiple conditions to sort. Most previous answers are not generic: they freeze the ordering at level 1.

df <- data.frame(values = rnorm(100),
                 sortcol1 = paste0("ASORT", sample(1:100, 100, replace = TRUE)),
                 sortcol2 = paste0("BSORT", sample(1:100, 100, replace = TRUE)),
                 stringsAsFactors = F)

df %>%
mutate(
    `sortcol1` = factor(`sortcol1`, ordered = T, levels = unique(gtools::mixedsort(`sortcol1`))),
    `sortcol2` = factor(`sortcol2`, ordered = T, levels = unique(gtools::mixedsort(`sortcol2`)))
) %>%
arrange(`sortcol1`, `sortcol2`)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.