【问题标题】:Create table with nested header from pre-summarized data从预先汇总的数据创建带有嵌套标题的表
【发布时间】:2017-03-24 16:11:15
【问题描述】:

如何从已经汇总的 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(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

我想要这样的东西:

             Color
               D          E          F          G          H          I         J
        cut    n   pct    n   pct    n   pct    n   pct    n   pct    n   pct   n   pct
       Fair  163  0.10  224  0.14  312  0.19  314  0.20  303  0.19  175  0.11 119  0.07
       Good  662  0.13  933  0.19  909  0.19  871  0.18  702  0.14  522  0.11 307  0.06
  Very Good 1513  0.13 2400  0.20 2164  0.18 2299  0.19 1824  0.15 1204  0.10 678  0.06
    Premium 1603  0.12 2337  0.17 2331  0.17 2924  0.21 2360  0.17 1428  0.10 808  0.06
      Ideal 2834  0.13 3903  0.18 3826  0.18 4884  0.23 3115  0.14 2093  0.10 896  0.04

以下是我能得到的最接近的示例。下表的问题是只有一个标题。我想要 3 行/标题:一个表示变量的名称:颜色,一个列出颜色内的各个类别,一个列出摘要类型(来自 df2$variable):

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

我希望有一些功能/包可以做到这一点。我认为这应该是可能的,因为包 etable 和表以及函数 ftable 可以创建我想要的输出,但不能用于预先汇总的数据。

此链接可以满足我的需要(我认为),但我只能访问我使用的服务器上的 CRAN 包。

https://www.r-statistics.com/2012/01/printing-nested-tables-in-r-bridging-between-the-reshape-and-tables-packages/

【问题讨论】:

标签: r


【解决方案1】:

基于 cmets 的解决方案。谢谢!

# 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 )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-17
    • 1970-01-01
    • 2021-06-29
    • 2023-03-19
    • 2019-09-18
    • 1970-01-01
    相关资源
    最近更新 更多