Search code examples
rsortingrow

Custom row order by mirrored column values


I have a dataset like this:

Tab1 <- read.table(text = "
   nodepair ES1 ++ -- +- -+ 0+ +0 0- -0 00 ES2
1     A1_A1   3  0  4  0  0  0  0  0  0 16   4
2     A1_A1   3  0  4  0  0  0  0  0  0 16   5
3     A1_A1   4  0  5  0  0  0  0  0  0 16   3
4     A1_A1   4  0  5  0  0  0  0  0  0 16   5
5     A1_A1   5  0  5  0  0  0  0  0  0 15   3
6     A1_A1   5  0  5  0  0  0  0  0  0 15   4
7     A2_A1   3  0  0  0  0  0  0  0  0 20   4
8     A2_A1   3  0  0  0  0  0  0  0  0 20   5
9     A2_A1   4  0  0  0  0  0  0  0  0 21   5
10    A2_A1   4  0  0  0  0  0  0  0  0 21   3
11    A2_A1   5  0  0  0  0  0  0  0  0 20   4
12    A2_A1   5  0  0  0  0  0  0  0  0 20   3   
", header = TRUE)

I need to order this first by nodepair, but then by both ES1 and ES2 such that the mirror combination of each ES1 and ES2 are sorted like this:

Tab2 <- read.table(text = "
   nodepair ES1 ++ -- +- -+ 0+ +0 0- -0 00 ES2
1     A1_A1   3  0  4  0  0  0  0  0  0 16   4
3     A1_A1   4  0  5  0  0  0  0  0  0 16   3
2     A1_A1   3  0  4  0  0  0  0  0  0 16   5
5     A1_A1   5  0  5  0  0  0  0  0  0 15   3
4     A1_A1   4  0  5  0  0  0  0  0  0 16   5
6     A1_A1   5  0  5  0  0  0  0  0  0 15   4
7     A2_A1   3  0  0  0  0  0  0  0  0 20   4
10    A2_A1   4  0  0  0  0  0  0  0  0 21   3
8     A2_A1   3  0  0  0  0  0  0  0  0 20   5
12    A2_A1   5  0  0  0  0  0  0  0  0 20   3
9     A2_A1   4  0  0  0  0  0  0  0  0 21   5
11    A2_A1   5  0  0  0  0  0  0  0  0 20   4    
", header = TRUE)

I've tried various versions of arrange and group by but can't seem to crack it


Solution

  • dplyr

    This is another solution using dplyr and ifelse

    library(dplyr)
    Tab1 %>%
      mutate(ES3=ifelse(ES1<ES2,paste(ES1,ES2,sep=','),paste(ES2,ES1,sep=','))) %>% 
      arrange(nodepair,ES3)