2017-03-23 22 views
0

如何根據已經彙總的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 $變量來):

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 

我希望有一些功能可以做到這一點。我認爲這應該是可能的,因爲packages etable和tables以及函數ftable可以創建我想要的輸出,但不能用於預先彙總的數據。

此鏈接做我需要的(我認爲),但我只能訪問我使用的服務器上的CRAN包。

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

+1

這需要顯示在哪裏?在控制檯中?在一個RMarkdown? HTML?導出到文本編輯器/電子表格? – GGamba

+1

對於預先計算的數據,您可以在「表格::表格」中使用「身份」,如在這裏:[在R中創建一個表,頭部使用xtable或任何包擴展到兩列上](http://stackoverflow.com/questions/17560683/create-a-table-in-r-with-header-expanding-on - 兩個柱-使用-xtable - 或任何-PAC)。 – Henrik

回答

0

解決方案基於評論。謝謝!

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