Skip to content

sorting dataframe by arbitrary order

3 messages · William Dunlap, Trevor Davies

#
Set the levels of the factor a$V1 to the order
in which you want them to be sorted.  E.g.,

  > a <- data.frame(V1=letters[rep(4:1,2)], V2=1001:1008)
  > a[do.call(order,a[c('V1','V2')]),]
    V1   V2
  4  a 1004
  8  a 1008
  3  b 1003
  7  b 1007
  2  c 1002
  6  c 1006
  1  d 1001
  5  d 1005
  > a$V1 <- factor(a$V1, levels=c("a","c","d","b"))
  > a[do.call(order,a[c('V1','V2')]),]
    V1   V2
  4  a 1004
  8  a 1008
  2  c 1002
  6  c 1006
  1  d 1001
  5  d 1005
  3  b 1003
  7  b 1007

This means that tables and plots will be ordered in
the way as well.  E.g.,

  > with(a, table(V1, V2))
     V2
  V1  1001 1002 1003 1004 1005 1006 1007 1008
    a    0    0    0    1    0    0    0    1
    c    0    1    0    0    0    1    0    0
    d    1    0    0    0    1    0    0    0
    b    0    0    1    0    0    0    1    0


Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com