0

This is similar to this: Arranging rows in custom order using dplyr But I am looking for different results...

v1 <- rep(LETTERS[1:3], each = 2)
v2 <- rep(c("Seg1", "Seg2"), times = 3)
v3<- c(300,200,500,700,600,550)
df<- data.frame(v1,v2,v3)

so that's my original df and we see the order A,A,B,B,C,C I want to change the order so it will be C,A,B,C,A,B I tried using

df %>%
    arrange(match(v1, c("C", "A", "B")), desc(v2), desc(v3))

but this gives us a result that looks like C,C,A,A,B,B

original df:

original df

results I want:

result I want

unwanted result I get:

unwanted result

lu-202
  • 121
  • 7
  • 2
    Your question is a bit unclear but I think you want `v2` as the primary key? `df[order(df$v2, match(df$v1, c("C", "A", "B"))),]` – Roland Jan 31 '22 at 06:51

1 Answers1

1
v1 <- rep(LETTERS[1:3], each = 2)
v2 <- rep(c("Seg1", "Seg2"), times = 3)
v3<- c(300,200,500,700,600,550)
df<- data.frame(v1,v2,v3)

library(tidyverse)
df %>% 
  arrange(v2, factor(v1, levels = c("C", "A", "B"))) 
#>   v1   v2  v3
#> 1  C Seg1 600
#> 2  A Seg1 300
#> 3  B Seg1 500
#> 4  C Seg2 550
#> 5  A Seg2 200
#> 6  B Seg2 700

Created on 2022-01-31 by the reprex package (v2.0.1)

Yuriy Saraykin
  • 8,390
  • 1
  • 7
  • 14