可旋转分组分组

时间:2018-09-24 10:00:27

标签: javascript r sorting rpivottable

由于rpivotTable中的R软件包,我用此代码生成了一个可旋转的表:

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包?

1 个答案:

答案 0 :(得分:0)

相对于您的回答,我可能从您的问题中学到的更多,因为我喜欢dplyr和JavaScript的巧妙结合。要重述您的问题,您在排序功能中指定了一个Eye排序列表,但是您确实希望根据Hair分组使用不同的Eye排序列表。因此,您的“眼睛”排序列表:

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\"]" 

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