Home > other >  Arrange rows in custom order in R using a vector
Arrange rows in custom order in R using a vector

Time:02-01

This is similar to this: original df

results I want:

result I want

unwanted result I get:

unwanted result

CodePudding user response:

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)

CodePudding user response:

If your dataset contains only six rows, we can slice() one part out, find out the difference between the sliced one and the original one, and bind them together.

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)

sequence <- c("C", "A", "B")

df2 <- df %>% slice(match(sequence, v1))

rbind(setdiff(df, df2) %>% slice(match(sequence,v1)), df2)

  v1   v2  v3
1  C Seg2 550
2  A Seg2 200
3  B Seg2 700
4  C Seg1 600
5  A Seg1 300
6  B Seg1 500

However, I do not think this is a smart way of doing it, since if you have more than two sets of "C", "A", "B", it becomes complicated.

  •  Tags:  
  • Related