1

I have dataframe that looks like this:

df<- data.frame("Logger" = c("1189_1", "1189_2","1189_3","1189_4","552_1","552_2","552_3","119_1","119_2","119_3","119_4","119_5"),
                         "Temp"  =c (4.5, 5.7, 3.8, 8.9, 8.6, 10.5, 11.0, 7.8, 5.6, 7.8, 9.9, 17.3),
                         "RH"    = c(6.5, 2.7, 11.8, 4.9, 3.6, 12.5, 115.0, 3.8, 9.6, 1.8, 3.9,5.3))

So the variable Logger is not sorted in the way I want it. It should be "119_x, 552_x, 1189_x". The last number after the "_" is sorted correctly, but everything before that is not. I understand how R sorts this, but like how can I order a char in a numeric way, if you know what I mean? Thanks a lot in advance! Cheers!

I tried mixedorder/mixedsort from the gtools package and str_order, but I get the error messages:

> tmp %>% mixedorder(tmp$Logger)
Error in order(c(2294053L, 2294053L, 2294053L, 2294053L, 2294053L, 2294053L,  : 
  'decreasing' elements must be TRUE or FALSE
> tmp %>% mixedsort(tmp$Logger)
Error in order(c(2294053L, 2294053L, 2294053L, 2294053L, 2294053L, 2294053L,  : 
  'decreasing' elements must be TRUE or FALSE
> tmp %>% str_order(tmp$Logger)
Error in stri_order(x, decreasing = decreasing, na_last = na_last, opts_collator = stri_opts_collator(locale,  : 
  missing value in argument `decreasing` is not supported
In addition: Warning message:
In stri_order(x, decreasing = decreasing, na_last = na_last, opts_collator = stri_opts_collator(locale,  :
  argument `decreasing` should be a single logical value; only the first element is used
zx8754
  • 52,746
  • 12
  • 114
  • 209
Effigy
  • 145
  • 7
  • 2
    mixedorder works fine, try: `df[ gtools::mixedorder(df$Logger), ]` – zx8754 Sep 22 '21 at 11:10
  • Thanks a lot, that works for some reason. Do you know what my mistake was? I also tried tmp$Logger %>% mixedsort(tmp$Logger) and it didnt work either. Got the same error as mentioned. – Effigy Sep 22 '21 at 12:31
  • 1
    If you are trying to use dplyr, try: `df %>% arrange(order(gtools::mixedorder(Logger)))` or `df %>% slice(gtools::mixedorder(Logger))`, see here: https://stackoverflow.com/q/32378108/680068 – zx8754 Sep 22 '21 at 13:27

0 Answers0