2

I want to know how to arrange data rows in by specific order of a particular grouping variable level in r.

Using the mtcars dataset, I want to create a data frame, called mtcars_arrange where rows are first organized by gear values in the following order:

> # desired gear order
> gear_order <- c(4, 3, 5)
> gear_order
[1] 4 3 5

Then, I want the dataset to be organized by a specific carb value:

> # desired carb order
> carb_order <- c(4, 1, 2, 3, 6, 8)
> carb_order
[1] 4 1 2 3 6 8

I know that you can use the dplyr::arrange() command to accomplish similar tasks, but I'm not sure what to do to get it to work for my purposes.

Any help would be appreciated. Thanks.



Here is some scrap code associated with this question:

# dataset
mtcars

# unique values of gear variable
unique(mtcars$gear)

# unique values of carb variable
unique(mtcars$carb)

# desired gear order
gear_order <- c(4, 3, 5)

# desired carb order
carb_order <- c(4, 1, 2, 3, 6, 8)
Mel
  • 510
  • 3
  • 10

1 Answers1

3

We could convert to factor with levels specified as the vector objects created in arrange

library(dplyr)
mtcars1 <- mtcars %>% 
     arrange(factor(gear, levels = gear_order), 
            factor(carb, levels = carb_order))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Cool. Thanks. Is there any way to do this by specifying an order based on an external list, or something like that? That is, if the ```unique()``` command didn't produce the desired order and the user had a specific order in mind, can you use ```arrange()``` to accomplish the task using an external list? – Mel Aug 16 '21 at 18:16
  • 1
    @Mel You can just specify `levels = yourvec1` yourvec2 for each columns – akrun Aug 16 '21 at 18:17
  • 1
    @Mel I used `unique` only because the ones you showed is based on `unique` order – akrun Aug 16 '21 at 18:18
  • 1
    Sorry, I thought I pressed the check. – Mel Aug 16 '21 at 18:34