![](/img/trans.png)
[英]How to sort multiple ascending/descending columns in a data.frame: R
[英]Sort a data frame in R by multiple columns at the same time
所以,我有一個大型數據框(7000行),其排列方式如下:
head(mx)
Stem Progenitor Astrocyte Neuron genename
ENSRNOG00000000007 0.0517698 0.700234 0.11753300 4.591050 Gad1
ENSRNOG00000000010 0.0536043 0.471518 0.00741803 2.280760 Cbln1
ENSRNOG00000000012 0.0163017 0.285178 1.89533000 0.268405 Tcf15
ENSRNOG00000000024 2.7904200 0.703727 13.96940000 4.944650 HEBP1
ENSRNOG00000000028 2.5059900 2.563040 4.83952000 0.840013 Nde1
ENSRNOG00000000029 1.6204500 2.928300 15.58360000 1.750350 Myh11
我需要對此數據幀進行排序,使其按前四列中的任何值從高到低排序。 因此,對於該示例,這5行的排序將是:
Stem Progenitor Astrocyte Neuron genename
ENSRNOG00000000029 1.6204500 2.928300 15.58360000 1.750350 Myh11
ENSRNOG00000000024 2.7904200 0.703727 13.96940000 4.944650 HEBP1
ENSRNOG00000000028 2.5059900 2.563040 4.83952000 0.840013 Nde1
ENSRNOG00000000007 0.0517698 0.700234 0.11753300 4.591050 Gad1
ENSRNOG00000000010 0.0536043 0.471518 0.00741803 2.280760 Cbln1
ENSRNOG00000000012 0.0163017 0.285178 1.89533000 0.268405 Tcf15
我知道我可以使用以下命令一次按一列對數據幀進行排序:
mx <- mx[with(mx, order(-Stem, -Progenitor, -Astrocyte, -Neuron)),]
但是,在上面的例子中,這將把Tcf15置於Gad1和Cbln1之上。 有沒有辦法按四列中的任何一列中的最高值排序? 我可以編寫一些腳本來手動迭代數據框並使用Rbind排序成一個新的數據框,但這非常低效,我相信有更好的方法來做到這一點。
使用pmax
四列中的最大值
mx <- mx[with(mx, order(-pmax(Stem, Progenitor, Astrocyte, Neuron))),]
使用dplyr,這是:
library(dplyr)
arrange(ms, desc(pmax(Stem, Progenitor, Astrocyte, Neuron)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.