Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep table dimnames in knitr or pander output?

I'm printing frequency tables using knit::kable and pander::pandoc, and generally this works great for HTML/Word/LaTeX output. But sometimes I'd like to preserve dimension names in the final product. Unfortunately, both pander and knitr drop these when converting to markdown.

# create a simple table
tab <- table(mtcars$gear, mtcars$carb)

# add dimension names
names(dimnames(tab)) <- c("gear", "carb")

This creates a table:

    carb
gear 1 2 3 4 6 8
   3 3 4 3 5 0 0
   4 4 4 0 4 0 0
   5 0 2 0 1 1 1

But now if we print with, say, kable:

> kable(tab)

|   |  1|  2|  3|  4|  6|  8|
|:--|--:|--:|--:|--:|--:|--:|
|3  |  3|  4|  3|  5|  0|  0|
|4  |  4|  4|  0|  4|  0|  0|
|5  |  0|  2|  0|  1|  1|  1|

No dimension names! (And ?kable does not indicate any option that would include them.)

Any suggestions for a tool that will preserve these? I've noticed that descr:CrossTable does the trick, but includes a whole lot of extra info I'd like to omit.

Many thanks.

like image 293
ChadBDot Avatar asked Dec 31 '15 19:12

ChadBDot


1 Answers

You can use eg ftable to create a flat contingency table implicitly having the dimension names:

> pander::pander(ftable(tab))

---- ---- - - - - - -
     carb 1 2 3 4 6 8

gear                 

 3        3 4 3 5 0 0

 4        4 4 0 4 0 0

 5        0 2 0 1 1 1
---- ---- - - - - - -

Or you can also suppress the not needed cells from descr::CrossTable such as:

> pander(descr::CrossTable(tab, prop.r = FALSE, prop.c = FALSE, prop.chisq = FALSE))

------------------------------------------------------------------------------
 &nbsp;\   carb\    &nbsp;\   &nbsp;\   &nbsp;\   &nbsp;\   &nbsp;\   &nbsp;\ 
  gear       1         2         3         4         6         8       Total  
--------- -------- --------- --------- --------- --------- --------- ---------
 **3**\   &nbsp;\  &nbsp;\   &nbsp;\   &nbsp;\   &nbsp;\   &nbsp;\   &nbsp;\  
   N\       3\       4\        3\        5\        0\        0\         15\   
Total(%)   9.375%   12.500%   9.375%    15.625%   0.000%    0.000%            

 **4**\   &nbsp;\  &nbsp;\   &nbsp;\   &nbsp;\   &nbsp;\   &nbsp;\   &nbsp;\  
   N\       4\       4\        0\        4\        0\        0\         12\   
Total(%)  12.500%   12.500%   0.000%    12.500%   0.000%    0.000%            

 **5**\   &nbsp;\  &nbsp;\   &nbsp;\   &nbsp;\   &nbsp;\   &nbsp;\   &nbsp;\  
   N\       0\       2\        0\        1\        1\        1\         5\    
Total(%)   0.000%   6.250%    0.000%    3.125%    3.125%    3.125%            

  Total      7        10         3        10         1         1        32    
------------------------------------------------------------------------------

Or submit a ticket on GH :)

like image 85
daroczig Avatar answered Oct 26 '22 04:10

daroczig