gpt4 book ai didi

javascript - 在 rpivottable 中分组排序

转载 作者:行者123 更新时间:2023-11-30 06:22:16 27 4
gpt4 key购买 nike

感谢 R 中的 rpivotTable 包,我已经使用这段代码生成了一个 rpivottable:

library("rpivotTable")
library("dplyr")
library("reshape2")

dane <- melt(HairEyeColor)

rpivotTable(dane,
rows = c("Hair", "Eye"),
cols = c("Sex"),
vals = "value",
aggregatorName = "Integer Sum",
locale = "en",
rendererName = "Table With Subtotal",
subtotals = TRUE)

看起来像这样:

enter image description here

它是按字母顺序排列的。我想使用值的总和按降序对其进行排序。

我可以这样尝试:

library("rpivotTable")
library("dplyr")
library("reshape2")

dane <- melt(HairEyeColor)

sorter <- paste0("function(attr) {",
"var sortAs = $.pivotUtilities.sortAs;",
"if (attr == \"Eye\") { return sortAs([\"",
dane %>% group_by(Eye) %>% summarise(i = sum(value)) %>% arrange(-i) %>% .$Eye %>% paste(collapse = "\", \""),
"\"]); }",
"if (attr == \"Hair\") { return sortAs([\"",
dane %>% group_by(Hair) %>% summarise(i = sum(value)) %>% arrange(-i) %>% .$Hair %>% paste(collapse = "\", \""),
"\"]); }",
"}")

rpivotTable(dane,
rows = c("Hair", "Eye"),
cols = c("Sex"),
vals = "value",
aggregatorName = "Integer Sum",
locale = "en",
rendererName = "Table With Subtotal",
subtotals = TRUE,
sorters = sorter)

我明白了:

enter image description here

这是按“外部”组排序的。我想像这里一样按两个组对它进行排序:

enter image description here

rpivotTable 包中可以吗?

最佳答案

我从你的问题中学到的可能比你从我的回答中学到的更多,因为我喜欢你巧妙地混合 dplyr 和 JavaScript。为了重申您的问题,您在排序器函数中指定了一个眼睛排序列表,但您确实需要一个不同的眼睛排序列表,具体取决于头发分组。所以你的眼睛排序列表:

library("dplyr")
library("reshape2")

dane <- melt(HairEyeColor)
dane %>% group_by(Eye) %>% summarise(i = sum(value)) %>%
arrange(-i) %>% .$Eye %>% paste(collapse = "\", \"")

...有这样的输出:

"Brown\", \"Blue\", \"Hazel\", \"Green"

...这与每个 头发分组中使用的排序顺序相同。另见 this answer .

我不是数据透视表方面的专家,但为了做你想做的事,我认为排序函数必须处理两个属性,比如 [\"Hair\",\"Eye\"],不止一个。我相信像这样的 dplyr 表达式会让你得到正确的二维列表:

dane %>% group_by(Hair, Eye) %>% 
summarise(hairEyeSum = sum(value)) %>%
ungroup() %>%
arrange( desc(hairEyeSum)) %>%
group_by( Hair) %>%
mutate( hairSum = sum(hairEyeSum)) %>%
arrange( desc(hairSum), desc(hairEyeSum)) %>%
ungroup() %>%
transmute( hairEyeList = paste0( "[\"", Hair, "\",\"", Eye, "\"]"))

输出:

# A tibble: 16 x 1
hairEyeList
<chr>
1 "[\"Brown\",\"Brown\"]"
2 "[\"Brown\",\"Blue\"]"
3 "[\"Brown\",\"Hazel\"]"
4 "[\"Brown\",\"Green\"]"
5 "[\"Blond\",\"Blue\"]"
6 "[\"Blond\",\"Green\"]"
7 "[\"Blond\",\"Hazel\"]"
8 "[\"Blond\",\"Brown\"]"
9 "[\"Black\",\"Brown\"]"
10 "[\"Black\",\"Blue\"]"
11 "[\"Black\",\"Hazel\"]"
12 "[\"Black\",\"Green\"]"
13 "[\"Red\",\"Brown\"]"
14 "[\"Red\",\"Blue\"]"
15 "[\"Red\",\"Hazel\"]"
16 "[\"Red\",\"Green\"]"

但我没有让排序器功能正常工作。

关于javascript - 在 rpivottable 中分组排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52476828/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com