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

前端 未结 10 1692
庸人自扰
庸人自扰 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:48

    Let df be the data frame with 2 fields A and B

    Case 1: if your field A and B are numeric

    df[order(df[,1],df[,2]),] - sorts fields A and B in ascending order
    df[order(df[,1],-df[,2]),] - sorts fields A in ascending and B in descending order
    priority is given to A.

    Case 2: if field A or B is non numeric say factor or character

    In our case if B is character and we want to sort in reverse order
    df[order(df[,1],-as.numeric(as.factor(df[,2]))),] -> this sorts field A(numerical) in ascending and field B(character) in descending.
    priority is given to A.

    The idea is that you can apply -sign in order function ony on numericals. So for sorting character strings in descending order you have to coerce them to numericals.

提交回复
热议问题