How to order a data frame by one descending and one ascending column?

前端 未结 10 1694
庸人自扰
庸人自扰 2020-12-02 13:02

I have a data frame, which looks like that:

    P1  P2  P3  T1  T2  T3  I1  I2
1   2   3   5   52  43  61  6   \"b\"
2   6   4   3   72  NA  59  1   \"a\"
3         


        
10条回答
  •  甜味超标
    2020-12-02 13:44

    In @dudusan's example, you could also reverse the order of I1, and then sort ascending:

    > rum <- read.table(textConnection("P1  P2  P3  T1  T2  T3  I1  I2
    +   2   3   5   52  43  61  6   b
    +   6   4   3   72  NA  59  1   a
    +   1   5   6   55  48  60  6   f
    +   2   4   4   65  64  58  2   b
    +   1   5   6   55  48  60  6   c"), header = TRUE)
    > f=factor(rum$I1)   
    > levels(f) <- sort(levels(f), decreasing = TRUE)
    > rum[order(as.character(f), rum$I2), ]
      P1 P2 P3 T1 T2 T3 I1 I2
    1  2  3  5 52 43 61  6  b
    5  1  5  6 55 48 60  6  c
    3  1  5  6 55 48 60  6  f
    4  2  4  4 65 64 58  2  b
    2  6  4  3 72 NA 59  1  a
    > 
    

    This seems a bit shorter, you don't reverse the order of I2 twice.

提交回复
热议问题