1

I have the following data.frame and would like to change the order of the rows in such a way that rows with variable == "C" come at the top followed by rows with "A" and then those with "B".

library(tidyverse)
set.seed(123)
D1 <- data.frame(Serial = 1:10, A= runif(10,1,5),
                 B = runif(10,3,6),
                 C = runif(10,2,5)) %>% 
     pivot_longer(-Serial, names_to = "variables", values_to = "Value" ) %>% 
  arrange(-desc(variables))
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
Hydro
  • 1,057
  • 12
  • 25

2 Answers2

1
D1 %>%
   mutate(variables = ordered(variables, c('C', 'A', 'B'))) %>%
   arrange(variables) 

Perhaps I did not get the question. If you want C then A then B, you could do:

D1 %>%
   arrange(Serial, variables) 
Onyambu
  • 67,392
  • 3
  • 24
  • 53
1

@Onyambu's answer is probably the most "tidyverse-ish" way to do it, but another is:

D1[order(match(D1$variables,c("C","A","B"))),]

or

D1 %>% slice(order(match(variables,c("C","A","B"))))

or

D1 %>% slice(variables %>% match(c("C","A","B")) %>% order())
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • Thank you Ben for suggesting another possible solution. – Hydro Jun 30 '21 at 22:52
  • 1
    @akrun, don't know. Maybe someone's having a bad day. I suspect this is a dupe, but didn't have the energy to look very hard/figure out a search strategy. Any ideas? – Ben Bolker Jun 30 '21 at 23:14