Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort rows of a data frame based on a vector using dplyr pipe

Tags:

r

dplyr

I have the following data frame:

library(tidyverse)
dat <- structure(list(var1 = c(1L, 2L, 2L, 3L, 1L), var2 = structure(c(10L, 
1L, 8L, 3L, 5L), .Label = c("b", "c", "f", "h", "i", "o", "s", 
"t", "w", "x"), class = "factor"), var3 = c(7L, 5L, 5L, 8L, 5L
), var4 = structure(c(8L, 5L, 1L, 4L, 7L), .Label = c("b", "c", 
"d", "e", "f", "h", "i", "w", "y"), class = "factor")), .Names = c("var1", 
"var2", "var3", "var4"), row.names = c(NA, 5L), class = "data.frame")


dat
#>   var1 var2 var3 var4
#> 1    1    x    7    w
#> 2    2    b    5    f
#> 3    2    t    5    b
#> 4    3    f    8    e
#> 5    1    i    5    i

What I want to do is to sort/arrange the var2 column based on a predefined order:

my_order <- c('t','f','x','b','i')

The final desired result is this:

  var1 var2 var3 var4
    2    t    5    b
    3    f    8    e
    1    x    7    w
    2    b    5    f
    1    i    5    i

I'd like to do it under dplyr piping. How can I achieve that?

At best I can do is this:

> dat  %>% 
+   arrange(var2)
  var1 var2 var3 var4
1    2    t    5    b
2    3    f    8    e
3    1    x    7    w
4    2    b    5    f
5    1    i    5    i
like image 476
scamander Avatar asked Sep 07 '18 06:09

scamander


2 Answers

We can use arrange with match

library(dplyr)

dat %>%
  arrange(match(var2, my_order))

#  var1 var2 var3 var4
#1    2    t    5    b
#2    3    f    8    e
#3    1    x    7    w
#4    2    b    5    f
#5    1    i    5    i
like image 173
Ronak Shah Avatar answered Nov 16 '22 09:11

Ronak Shah


We can convert the column to a factor with levels specified as 'my_order' (but it doesn't change the type of the actual column)

library(dplyr)
dat %>% 
    arrange(factor(var2, levels = my_order))
#  var1 var2 var3 var4
#1    2    t    5    b
#2    3    f    8    e
#3    1    x    7    w
#4    2    b    5    f
#5    1    i    5    i
like image 43
akrun Avatar answered Nov 16 '22 08:11

akrun