Order a matrix by multiple column in r

前端 未结 3 1993
礼貌的吻别
礼貌的吻别 2020-12-25 12:58

I have a matrix

df<-matrix(data=c(3,7,5,0,1,0,0,0,0,8,0,9), ncol=2)
rownames(df)<-c(\"a\",\"b\",\"c\",\"d\",\"e\",\"f\")

[,1] [,2]
a    3    0
b    7          


        
3条回答
  •  一向
    一向 (楼主)
    2020-12-25 13:48

    order function will help you out, try this:

    df[order(-df[,1],-df[,2]),] 
      [,1] [,2]
    b    7    0
    c    5    0
    a    3    0
    e    1    0
    f    0    9
    d    0    8
    

    The minus before df indicates that the order is decreasing. You will get the same result setting decreasing=TRUE.

    df[order(df[,1],df[,2],decreasing=TRUE),]
    

提交回复
热议问题