R 从预先汇总的数据创建具有嵌套标题的表
如何从已经汇总的data.frame创建嵌套表?通过嵌套,我的意思是表格有标题和副标题 我的输入数据如下所示:R 从预先汇总的数据创建具有嵌套标题的表,r,R,如何从已经汇总的data.frame创建嵌套表?通过嵌套,我的意思是表格有标题和副标题 我的输入数据如下所示: library(ggplot2) library(reshape2) df <- ggplot2::diamonds count(df, cut,color) %>% mutate( n = n, pct = round(n / sum(n),2) ) %>% reshape2::melt() -> df2 head(df2 ) > head
library(ggplot2)
library(reshape2)
df <- ggplot2::diamonds
count(df, cut,color) %>% mutate(
n = n,
pct = round(n / sum(n),2) ) %>% reshape2::melt() -> df2
head(df2 )
> head(df2 )
cut color variable value
1 Fair D n 163
2 Fair E n 224
3 Fair F n 312
4 Fair G n 314
5 Fair H n 303
6 Fair I n 175
下面是我能得到的最接近的例子。下表的问题是只有一个标题。我想要3行/标题:一行表示变量名称:Color,一行列出Color中的各个类别,另一行列出摘要类型(来自df2$variable):
我希望有一些功能/软件包可以做到这一点。我认为这应该是可能的,因为包etable和表以及函数ftable可以创建我想要的输出,但不能用于预汇总的数据
这个链接满足了我的需要(我想),但我只能访问我使用的服务器上的CRAN包
基于评论的解决方案。谢谢
# data
library(tidyr)
library(dplyr)
library(ggplot2)
library(reshape2)
df <- ggplot2::diamonds
count(df, cut,color) %>% mutate(
n = n,
pct = round(n / sum(n),2) ) %>% reshape2::melt() -> df2
head(df2 )
# Solution
spread( data = df2, key = variable, value = value ) -> df2_spread
tabular( Heading() * cut ~ color * (n + pct) * Heading() * (identity), data =df2_spread )
#数据
图书馆(tidyr)
图书馆(dplyr)
图书馆(GG2)
图书馆(E2)
df%变异(
n=n,
pct=四舍五入(n/和(n),2))%>%Reformate2::melt()->df2
主管(df2)
#解决方案
排列(数据=df2,键=变量,值=值)->df2\u排列
表格格式(标题()*切割~颜色*(n+pct)*标题()*(标识),数据=df2\U排列)
需要在哪里显示?在控制台里?在大减价中?HTML?导出到文本编辑器/电子表格?对于预先计算的数据,您可以在表格::表格中使用标识,如所述,例如:此处:。
reshape2::dcast(df2, cut ~ color + variable , value.var = c("value") )
cut D_n D_pct E_n E_pct F_n F_pct G_n G_pct H_n H_pct I_n I_pct J_n J_pct
1 Fair 163 0.10 224 0.14 312 0.19 314 0.20 303 0.19 175 0.11 119 0.07
2 Good 662 0.13 933 0.19 909 0.19 871 0.18 702 0.14 522 0.11 307 0.06
3 Very Good 1513 0.13 2400 0.20 2164 0.18 2299 0.19 1824 0.15 1204 0.10 678 0.06
4 Premium 1603 0.12 2337 0.17 2331 0.17 2924 0.21 2360 0.17 1428 0.10 808 0.06
5 Ideal 2834 0.13 3903 0.18 3826 0.18 4884 0.23 3115 0.14 2093 0.10 896 0.04
# data
library(tidyr)
library(dplyr)
library(ggplot2)
library(reshape2)
df <- ggplot2::diamonds
count(df, cut,color) %>% mutate(
n = n,
pct = round(n / sum(n),2) ) %>% reshape2::melt() -> df2
head(df2 )
# Solution
spread( data = df2, key = variable, value = value ) -> df2_spread
tabular( Heading() * cut ~ color * (n + pct) * Heading() * (identity), data =df2_spread )