【问题标题】:order a data.table based on a character column with a specific (not alphabetical) order in mind根据具有特定(非字母顺序)顺序的字符列对 data.table 进行排序
【发布时间】:2017-03-02 18:57:37
【问题描述】:

我想根据手动指定的字符向量订购数据表。

library(data.table)
DT = data.table(x=c("c","b","a"), y=1:3)

我可以按字母顺序排序:

DT[order(x)]

但我可以根据如下字符向量对其进行排序:

preferred.order <- c("b","a","c")

目标是:

data.table(x=c("b","a","c"), y=c(2,1,3))

实际上,我有一个 data.table,其中包含收集的输出和第一列中的变量名称。出于演示目的,我希望这些变量按特定(非字母)顺序。

【问题讨论】:

    标签: r data.table


    【解决方案1】:

    一种可能性是按首选顺序加入:

    DT[preferred.order, on="x"]
       x y
    1: b 2
    2: a 3
    3: c 1
    

    请注意,这要求preferred.order 向量包含DT$x 中的所有元素并且没有重复项。

    作为替代方案,您可以使用首选排序创建一个因子变量 DT$x,然后使用 setorder 通过引用对 DT 进行排序。

    DT[, xFac := factor(x, levels=preferred.order)]
    setorder(DT, xFac)
    

    返回

    DT
       x y xFac
    1: b 2    b
    2: a 3    a
    3: c 1    c
    

    哪种方法更可取将因用例而异。

    【讨论】:

    • 因子变量有效。好主意!我认为一个也可以处理重复项(我没有)。
    猜你喜欢
    • 2023-01-21
    • 1970-01-01
    • 2011-04-03
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多