0

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.

green diod
  • 1,399
  • 3
  • 14
  • 29
  • Would you consider using kable() or pander()? The output from pander() looks pretty good in HTML, PDF and MS Word. It doesn't require changing the print "type", as is required by xtable in my answer below. The absence of column names does look a little funny in Word. – Mark Miller Oct 24 '16 at 14:55

1 Answers1

1

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)

```
Mark Miller
  • 3,011
  • 1
  • 14
  • 34
  • Priority is pdf output, so it's fine. Actually, I found out that I could directly transpose the above data frame (all the data are just coerced to char) if the goal is just to print the table. Thanks. By the way, there should be no need to coerce `dset.print[ ,1]` – green diod Oct 24 '16 at 15:53
  • Actually, one needs to coerce `dset.print[, 1]`. I didn't expect this behavior! – green diod Oct 24 '16 at 16:12
  • I believe dset.print[, 1] contains the bin labels... you're calling them `smth`, right? They start out as factors. If you don't coerce them, you could really get confused because the factor numbers will be returned. In this case, the smth factors at {1,2,3...} and the bins from the poisson distribution are {0,1,2...} – Mark Miller Oct 24 '16 at 16:54