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
extract(dummydf, sortcol, c("sort1", "sort2"), "([A-Z]+)(\\d+)", convert = TRUE) %>% arrange(sort1, sort2)
data.table
answer?gtools::mixedsort
?