Print a frequency table of a factor with kable in rmarkdown

5.6k views Asked by At

I have a factor in R, that consists of the levels a, b and c. The data consists of 2 a's, one b and no c. I want to get an output like this (frequency of the elements according to the levels):

fac <- factor(c("a", "b", "a"), levels=c("a", "b", "c"))
tbl <- table(fac)
tbl

## fac
## a b c 
## 2 1 0

This should be printed with knitr/kable in a nice html table:

library(knitr)
kable(tbl)

But here comes the error:

"Error in dn[[2L]] : subscript out of bounds".

I assume that there is an issue with the dimnames of the table:

attributes(tbl)
## $dim
## [1] 3
## 
## $dimnames
## $dimnames$fac
## [1] "a" "b" "c"
## 
## 
## $class
## [1] "table"

Is there any option to "repair" the dimnames for kable? I just want to print this "simple" table - maybe I am stuck with something easy?

The usage of "table" with factors is described here: http://www.stat.berkeley.edu/~s133/factors.html

I read a lot about the 'pander'-package in the recent days. If I print the table with pander, it works. Why? Should I just switch to pander?

pander(tbl)
1

There are 1 answers

2
RHertel On BEST ANSWER

You could try

> kable(t(as.matrix(tbl)))
#
#|  a|  b|  c|
#|--:|--:|--:|
#|  2|  1|  0|