Home > Software engineering >  Ordering a dataframe based on a custom vector
Ordering a dataframe based on a custom vector

Time:04-22

Let say I have below dataframe in R

dat = data.frame('col1' = letters[1:10], 'col2' = c('A', 'X', 'D', 'Y', 'A', 'D', 'Y', 'X', 'D', 'A'))

I want to first order this dataframe w.r.t the col2 based on a defined vector c('D', 'Y', 'X', 'A') and then again order based on col1 but in descending order.

Is there any way to achieve this in R?

CodePudding user response:

Use a factor to define the ordering and use desc to invert it:

library(dplyr)

dat <- data.frame('col1' = letters[1:10], 'col2' = c('A', 'X', 'D', 'Y', 'A', 'D', 'Y', 'X', 'D', 'A'))

dat <-
  dat %>%
  mutate(
    col2 = col2 %>% factor(levels = c('D', 'Y', 'X', 'A'))
  )

dat %>% arrange(col2)
#>    col1 col2
#> 1     c    D
#> 2     f    D
#> 3     i    D
#> 4     d    Y
#> 5     g    Y
#> 6     b    X
#> 7     h    X
#> 8     a    A
#> 9     e    A
#> 10    j    A
dat %>% arrange(desc(col1))
#>    col1 col2
#> 1     j    A
#> 2     i    D
#> 3     h    X
#> 4     g    Y
#> 5     f    D
#> 6     e    A
#> 7     d    Y
#> 8     c    D
#> 9     b    X
#> 10    a    A

CodePudding user response:

Here is a way using left_join:

library(dplyr)

vector <- c('D', 'Y', 'X', 'A') 

left_join(data.frame(col2 = vector),    # Reorder data frame
                       dat,
                       by = "col2") %>% 
  arrange(desc(col1))
                          
   col2 col1
1     A    j
2     D    i
3     X    h
4     Y    g
5     D    f
6     A    e
7     Y    d
8     D    c
9     X    b
10    A    a
  • Related