Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a sort of mixed values in R

I have a data frame that I want to sort by one column than the next, (using tidyverse if possible).

I checked the below address but the solutions did not seem to work.

Order a "mixed" vector (numbers with letters)

Sample code for an example:

variable <- c("channel", "channel", "channel", "comp_ded", "comp_ded", "comp_ded")
level <- c("DIR", "EA", "IA", "500", "750", "1000")
df <- as_tibble(cbind(variable, level))

This does not give me what I want:

df <- df %>% arrange(variable, level)

The order of the level columns are as follows:

variable level channel DIR channel EA channel IA level 1000 level 500 level 750

I need them:

variable level channel DIR channel EA channel IA level 500 level 750 level 1000

There are multiple different "variables" in the real data set where half need to be sorted in number order and half in alphabetical. Does anyone know how to do this?

like image 564
Jordan Avatar asked Jan 03 '23 14:01

Jordan


1 Answers

The simplest solution would be to use dplyr::group_by.

library(dplyr)

variable <- c("channel", "channel", "channel", "comp_ded", "comp_ded", "comp_ded")
level <- c("DIR", "EA", "IA", "500", "750", "1000")
df <- as_tibble(cbind(variable, level))

df %>%
  group_by(variable, level) %>%
  arrange()

# A tibble: 6 x 2
  variable  level
     <chr> <fctr>
1 comp_ded    DIR
2 comp_ded     EA
3 comp_ded     IA
4  channel    500
5  channel    750
6  channel   1000
like image 198
zlipp Avatar answered Jan 13 '23 13:01

zlipp