【发布时间】:2016-09-03 13:10:43
【问题描述】:
我经常发现自己使用 dplyr 在 R 中计算汇总统计数据,然后将结果写入 csv 并将其加载到 Tableau 中以生成表格,因为 Tableau 的表格非常简单易行。我宁愿直接在 R 中生成表格。
R 中的分组表有简单的解决方案吗?
生成我想要的数据非常容易:
library(tidyr)
library(dplyr)
summary_table <- iris %>%
gather(measure, value, -Species) %>%
separate(measure, into=c("attribute", "dimension")) %>%
group_by(Species, attribute, dimension) %>%
summarise(mean=mean(value))
summary_table
Source: local data frame [12 x 4]
Groups: Species, attribute [?]
Species attribute dimension mean
<fctr> <chr> <chr> <dbl>
1 setosa Petal Length 1.462
2 setosa Petal Width 0.246
3 setosa Sepal Length 5.006
4 setosa Sepal Width 3.428
5 versicolor Petal Length 4.260
6 versicolor Petal Width 1.326
7 versicolor Sepal Length 5.936
8 versicolor Sepal Width 2.770
9 virginica Petal Length 5.552
10 virginica Petal Width 2.026
11 virginica Sepal Length 6.588
12 virginica Sepal Width 2.974
现在我想将其呈现为:
我想尝试几种不同的组织方式,所以我希望能够轻松地按行而不是按列进行分组
分组行版本的主要特点是:
- 分组变量位于左侧,在一个单独的列中,而不是在一个单独的行中,在一个跨越所有行的单元格中
- 组级别的水平单元格边框
我是 rmarkdown 的新手,但最终目标是将其包含在 html 文档中。
这可能吗?
【问题讨论】:
-
您也可以考虑自己进行聚合。我尝试了
aggregate(x = iris[, colnames(iris)[ colnames(iris) != "Species" ] ], by = list(iris$Species), FUN = function(y){ ifelse(is.numeric(y),mean(y),NA) } )。
标签: r knitr r-markdown pandoc