【问题标题】:Sort a data frame in R by multiple columns at the same time同时按多列对R中的数据框进行排序
【发布时间】:2014-08-03 21:48:59
【问题描述】:

所以,我有一个大数据框(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

我需要对这个数据框进行排序,使其按前四列中的 any 值从高到低排序。因此,例如,这 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 排序到一个新的数据框,但这非常低效,我相信有更好的方法来做到这一点。

【问题讨论】:

标签: r sorting dataframe


【解决方案1】:

使用pmax对四列中的最大值排序

mx <- mx[with(mx, order(-pmax(Stem, Progenitor, Astrocyte, Neuron))),]

【讨论】:

  • @Reed:我没有将他的数据读入 R 会话。我的答案来自记忆,未经测试。
【解决方案2】:

使用 dplyr,这是:

library(dplyr)
arrange(ms, desc(pmax(Stem, Progenitor, Astrocyte, Neuron)))

【讨论】:

    猜你喜欢
    • 2010-11-20
    • 2021-10-29
    • 2022-12-18
    • 2016-07-28
    • 2014-06-02
    • 2021-03-27
    • 2019-10-14
    相关资源
    最近更新 更多