How to sort dataframe in R with specified preservation of column order?

Say I have data.frame

x <- data.frame(a = c('A','A','A','A','A', 'C','C','C','C', 'B','B','B'), b = c('a','c','a','a','c', 'd', 'e','e','d', 'b','b','b'), c = c( 7, 3, 2, 4, 5, 3, 1, 1, 5, 5, 2, 3), stringsAsFactors = FALSE) > x abc 1 A a 7 2 A c 3 3 A a 2 4 A a 4 5 A c 5 6 C d 3 7 C e 1 8 C e 1 9 C d 5 10 B b 5 11 B b 2 12 B b 3 

I would like to sort x by columns b and c, but keeping the order of a, as before. x[order(x$b, x$c),] - interrupts the order of column a. This is what I want:

  abc 3 A a 2 4 A a 4 1 A a 7 2 A c 3 5 A c 5 6 C d 3 9 C d 5 7 C e 1 8 C e 1 11 B b 2 12 B b 3 10 B b 5 

Is there a quick way to do this?

I am currently running a pro loop and sorting each subset, I am sure there should be a better way.

Thanks! Ilya

+7
sorting r dataframe
source share
3 answers

If column "a" is already ordered, then its simple:

 > x[order(x$a,x$b, x$c),] abc 3 A a 2 4 A a 4 1 A a 7 2 A c 3 5 A c 5 6 B d 3 9 B d 5 7 B e 1 8 B e 1 11 C b 2 12 C b 3 10 C b 5 

If column a is not ordered (but grouped), create a new coefficient with levels x $ a and use this.

+7
source share

Thank Spacedman Your recommendation works well.

 x$a <- factor(x$a, levels = unique(x$a), ordered = TRUE) x[order(x$a,x$b, x$c),] 

After Gavin's comment

  x$a <- factor(x$a, levels = unique(x$a)) x[order(x$a,x$b, x$c),] 
0
source share
 require(doBy) orderBy(~ a + b + c, data=x) 
0
source share

All Articles