使用可变列重新排序 data.table

Reorder data.table with variable columns

我有一个 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

然后我可以使用 shiny select 我想根据哪个 ID 进行分组,例如 ID1 到 ID3:

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

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

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

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

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

我尝试使用 setcolorder,但是列可能因 select 编辑的 ID 而异。使用的 ID 存储在一个向量中,我尝试这样使用它:

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

和:

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

但这两个选项都不起作用

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

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

也许以下使用 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

setcolorder:

的更多尝试后设法找到了解决方案
setcolorder(dt, c(vector, "percentage", colnames(dt)[!(colnames(dt) %in% vector) & !(colnames(dt) == "percentage")]))

development version 1.14.3 of setcolorder()获得了新的参数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")