【问题标题】:order data.frame on non-numerical value在非数值上订购 data.frame
【发布时间】:2011-12-12 23:54:02
【问题描述】:

我有一个如下所示的 data.frame:

320    Dutch  A7     3

321    Dutch  A8     3

322    Dutch  A9     4

323    Dutch A10     1

324    Dutch A11     4

327    Dutch A14     4

325    Dutch A12     3

328    Dutch A15    10

326    Dutch A13     1

329    Dutch A16     3

我如何订购它,以便所有A1, A2, etc. 按字母和数字顺序排列,以便我得到:

320    Dutch  A7     3

321    Dutch  A8     3

322    Dutch  A9     4

323    Dutch A10     1

324    Dutch A11     4

325    Dutch A12     3

326    Dutch A13     1

327    Dutch A14     4

328    Dutch A15    10

329    Dutch A16     3

谢谢!

【问题讨论】:

    标签: r sorting


    【解决方案1】:

    你有点回答了你自己的问题。请参阅order 函数的帮助。另见this rant。

    【讨论】:

    • 你说得对,可以使用 order() - 我只是认为它仅用于数字。这是我使用的: Dutch2
    【解决方案2】:

    暂时忘记数据框部分。这是您要订购的样本向量

    x <- paste(
      rep.int(LETTERS[1:3], 16),
      rep.int(1:16, 3),
      sep = ""
    )
    y <- sample(x)
    

    仅仅调用sort(y) 是行不通的,因为数字会按字典顺序排序,所以你会得到类似 A1、A10、A11...

    改为使用substring 将列拆分为一个字母和一个数字。

    indexer <- data.frame(
      letter = substring(y, 1, 1),
      number = as.numeric(substring(y, 2))
    )
    

    然后,按照 aL3xa 的建议,调用 order 对生成的数据帧进行排序。

    o <- with(indexer, order(letter, number))
    y[o]
    

    要使其适用于数据框,只需将 y 替换为 your_data$index_column。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 2018-09-24
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多