Search code examples
rdplyrgroupingarrange-act-assert

How to arrange data rows in by specific order of a particular grouping variable level in r


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)

Solution

  • 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))