green diod green diod - 1 month ago 9
R Question

r xtable and table of frequencies, printing rowwise

xtable
doesn't know at the moment how to print tables of frequencies from
base::table
. What I do now is I convert it to a dataframe and then I change the headings using
colnames
as needed:

dset <- data.frame(rpois(100, 1))
dset.print <- as.data.frame(table(dset))
colnames(dset.print) <- c("smth", "freq")
xtable(dset.print)


Now, what I'd like is to print this table rowwise (like the actual output of
table(dset)
with the headings at the front). I tried something like this

dset.print <- t(as.matrix(table(dset)))
dset.print <- cbind(c("smth", "freq"), as.data.frame(dset.print))


But this didn't exactly give what I wanted.

Answer

This looks pretty good if you're knitting to PDF. If you're knitting to MS Word or HTML, specify print(dset.xtab, type="html") You may not find the aesthetics of those as nice.

```{r xtable, echo=FALSE, message=FALSE, warning=FALSE, results='asis'}
library(xtable)

dset <- data.frame(rpois(100, 1))

dset.print <- as.data.frame(table(dset))
dset.print <- rbind.data.frame(as.character(dset.print[,1]), dset.print[,2])
names(dset.print) <- rep('', ncol(dset.print))
rownames(dset.print) <- c('smth', 'freq')

dset.xtab <- xtable(dset.print)

print(dset.xtab)

```