Preserve row/column labels from table() using kable and knitr
@Yihui should get the credit for this. Straight from the printr
package:
# BEGINNING of Rmd file:```{r echo=FALSE}# devtools::install_github("yihui/printr")require(printr)# reproducibilityset.seed(123) # here's a dfsome_data <- data.frame(a=sample(c('up','down'), 10, replace=T), b=sample(c('big','small'), 10, replace=T))table(some_data)```# End of Rmd file
Results in:
|a/b | big| small||:----|---:|-----:||down | 5| 1||up | 0| 4|
Neat that someone else posted a bounty on my old question. Anyway, if it's helpful, my solution was a homebrew html generator function
table_label <- function(tbl) { # table dimensions rows <- dim(tbl)[1] cols <- dim(tbl)[2] # get started html_out <- '<table>\n' # first row: label only blank_cell <- '<td> </td>' html_out <- paste0(html_out, '\t<tr>', blank_cell, '<td>', names(dimnames(tbl))[2], '</td>', # column label rep(blank_cell, cols-2), '</tr>\n') # second row: html_out <- paste0(html_out, '\t<tr>', # label... '<td>', names(dimnames(tbl))[1], '</td>', # ...and headers paste0('<td>', dimnames(tbl)[[2]], '</td>', collapse=''), '</tr>\n') # subsequent rows for (i in 1:rows) { html_out <- paste0(html_out, '\t<tr>', # header... '<td>', dimnames(tbl)[[1]][i], '</td>', # ...and values paste0('<td>', tbl[i,], '</td>', collapse=''), '</tr>\n') } # last row html_out <- paste0(html_out, '</table>') return(html_out)}
Now this markdown doc:
Produce table```{r}set.seed(123) some_data <- data.frame(a=sample(c('up','down'), 10, replace=T), b=sample(c('big','small', 'medium'), 10, replace=T))tbl <- table(some_data)```Now display```{r, results='asis'}cat(table_label(tbl))```
Produces the results I had wanted:
The generated html is somewhat readable, too:
<table> <tr><td> </td><td>b</td><td> </td></tr> <tr><td>a</td><td>big</td><td>medium</td><td>small</td></tr> <tr><td>down</td><td>4</td><td>0</td><td>2</td></tr> <tr><td>up</td><td>0</td><td>4</td><td>0</td></tr></table>
Not an optimal solution (as Pandoc's markdown does not support col/rowspans), but give a try to pander, which is intended to transform R objects into markdown with ease (and bunch of options):
> library(pander)> pander(ftable(some_data))------ --- ----- ------- "b" "big" "small" "a" "down" 5 1 "up" 0 4 ------ --- ----- -------> pander(ftable(some_data), style = 'rmarkdown')| | | | ||:------:|:---:|:-----:|:-------:|| | "b" | "big" | "small" || "a" | | | || "down" | | 5 | 1 || "up" | | 0 | 4 |