【问题标题】:Reorder data.table with variable columns使用可变列重新排序 data.table
【发布时间】:2021-11-21 12:51:12
【问题描述】:

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

ID1 ID2 ID3 ID4 subtotal total
001 001 001 001 10 100
001 001 001 002 5 20
001 002 001 001 10 200

然后我可以使用闪亮选择要分组的 ID,例如 ID1 到 ID3:

ID1 ID2 ID3 subtotal total
001 001 001 15 120
001 002 001 10 200

如您所见,该表的第一行是第一个表的前两行的总和。

然后我计算百分比,该列将自动放在最后:

ID1 ID2 ID3 subtotal total percentage
001 001 001 15 120 12.5
001 002 001 10 200 5

但是,我希望在 ID 之后看到此列。

我尝试使用setcolorder,但列可能会因选择的 ID 而异。使用的 ID 存储在我尝试使用的向量中:

dt[, .(vector, percentage, subtotal, total)]

和:

dt[, c(vector, "percentage", "subtotal", "total")]

但这两种方法都不起作用

供参考(请记住,它应该适用于任何 ID 组合):

dput(vector)
c("ID1", "ID2", "ID3")

【问题讨论】:

标签: r shiny data.table


【解决方案1】:

也许以下使用dplyr 的解决方案对您有用。它会将百分比列紧跟在与"id" 模式匹配的所有列之后。列的实际重新排序发生在 relocate() 调用中。

df %>%
  group_by(id1, id2, id3) %>%
  summarise(subtotal = sum(subtotal),
            total = sum(total),
            percent = subtotal / total * 100) %>%
  relocate(percent, .after = contains("id"))

  id1   id2   id3   percent subtotal total
  <chr> <chr> <chr>   <dbl>    <dbl> <dbl>
1 001   001   001      12.5       15   120
2 001   002   001       5         10   200

【讨论】:

  • 感谢您的回复。这通常是我正在寻找的,除了我想将其保留为 data.table 格式而不是回到 data.frame
  • relocate()之后重新转换是否可以接受?您可以添加另一个管道并使用data.table()
  • 我正在考虑这样做,但同时我想出了另一种不使用dplyr 的方法,所以我会坚持下去
  • 很公平。如果不需要,则无需进行大的更改。
【解决方案2】:

在玩了更多 setcolorder 之后设法找到了解决方案:

setcolorder(dt, c(vector, "percentage", colnames(dt)[!(colnames(dt) %in% vector) & !(colnames(dt) == "percentage")]))

【讨论】:

    【解决方案3】:

    中的development version 1.14.3setcolorder() 获得了新的参数before 以及after 来指示插入列的位置:

    setcolorder(dt, "percentage", before = "subtotal")
    dt
    
       ID1 ID2 ID3 percentage subtotal total
    1:   1   1   1       12.5       15   120
    2:   1   2   1        5.0       10   200
    

    数据

    library(data.table)
    dt <- fread("
    ID1 ID2 ID3 subtotal    total   percentage
    001 001 001 15  120 12.5
    001 002 001 10  200 5")
    

    【讨论】:

      猜你喜欢
      • 2013-04-14
      • 2012-08-27
      • 2012-07-03
      • 2010-11-05
      • 1970-01-01
      • 2017-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多