Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve row/column labels from table() using kable and knitr

The table function in base R adds nice row/column labels, but when I use knitr::kable these go away. Any simple way to keep these, aside from adding them on the html/markdown side?

Reproducible example:

library(knitr)

# reproducibility
set.seed(123) 

# here's a df
some_data <-
  data.frame(a=sample(c('up','down'), 10, replace=T),
             b=sample(c('big','small'), 10, replace=T))

# using table() you get nice labels ('a' and 'b', in this case)
table(some_data)

enter image description here

# that goes away with kable, in either markdown or html format (I care about html)
kable(table(some_data))
kable(table(some_data), format='html')

enter image description here

like image 989
arvi1000 Avatar asked Oct 17 '14 16:10

arvi1000


People also ask

What does Kable do in R?

The kable() function in knitr is a very simple table generator, and is simple by design. It only generates tables for strictly rectangular data such as matrices and data frames. You cannot heavily format the table cells or merge cells.

What is Kable?

Kable is a 3PL Provider Who Helps E-Retailers, Subscription Box Companies, and Consumer Brands Succeed Wherever You Sell-Your Website, Amazon, or Online Marketplaces.

How do you insert a table in R markdown?

Upon installing, inserttable registers a new RStudio Addin (Insert Table) that can be used to easily insert a table in a Rmd document. To use it, open a Rmd or R document and select “Addins –> Insert Table”.


1 Answers

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

# reproducibility
set.seed(123) 

# here's a df
some_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|
like image 180
mikeck Avatar answered Sep 24 '22 01:09

mikeck