在Knitr中打印漂亮的交叉表 [英] Printing nice cross-tabulations in knitr
问题描述
我想要的是使用R,Markdown和knitr在RStudio中以pdf文件或html文件的形式打印漂亮的交叉表.我怀疑我缺少真正明显的东西,因为我不敢相信这是如此困难.我使用xtabs或ftable制作交叉表.
What I want is to print nice crosstabulations, either in a pdf file, or in a html file, from RStudio, using R, Markdown and knitr. I suspect I am missing something really obvious, because I cannot believe this is so hard. I make cross-tabs with either xtabs or ftable.
我想要的是类似R控制台输出的精美印刷版.
What I want is something like a nicely printed version of the R console output.
> x
Col
Row A B C
D 15 9 7
E 13 14 9
F 8 8 17
> f
Col A B C
Row
D 15 9 7
E 13 14 9
F 8 8 17
我尝试了几种不同的解决方案,但都没有真正起作用,这些解决方案在所附的.Rmd文件中显示. (我尝试过pdf和html输出.)
I've tried several different solutions, none of which really works, and are shown in the attached .Rmd file. (I've tried pdf and html outputs.)
---
title: "trial"
author: "Anthony Staines"
date: "26/08/2014"
output: html_document
---
# Make the data
```{r, echo=TRUE,results='asis',message=FALSE}
library(knitr)
library(memisc)
library(xtable)
library(stargazer)
library(texreg)
set.seed(893)
Col <- sample(c('A','B','C'),100,replace=TRUE)
Row <- sample(c('D','E','F'),100,replace=TRUE)
```
```{r, echo=TRUE,results='asis',message=FALSE}
x <- xtabs(~Row+Col)
x
kable(x)
kable(x,format='html')
kable(x,format='html',output = TRUE)
xx <- xtable(format(x))
print(xx,type='html')
stargazer(x)
f <-ftable(Row,Col)
f
kable(f,format='html')
kable(f,format='html',output = TRUE)
xf <- xtable(format(f))
print(xf,type='html')
stargazer(f)
```
kable最接近,但似乎不支持行名或列名,这对我来说都是必不可少的:-
kable comes closest, but does not seem to support row or column names, both of which are essential to me :-
| | A| B| C|
|:--|--:|--:|--:|
|D | 15| 9| 7|
|E | 13| 14| 9|
|F | 8| 8| 17|
感谢您的帮助,如果这是一个非常愚蠢的问题,并且有一个显而易见且众所周知的答案,我深表歉意!
Help appreciated, and my apologies if this is a really stupid question with an obvious and well known answer!
安东尼·斯坦斯
推荐答案
kable
的替代方法是使用相同名称的包中的pander
,它提供了一种生成带有一堆选项的减价表的简便方法(例如style
)和通用的S3方法:
An alternative to kable
is pander
from the package with the same name, which provides an easy way of generating markdown tables with bunch of options (like style
) and a generic S3 method:
> pander(x)
-------------------
A B C
------- --- --- ---
**D** 15 9 7
**E** 13 14 9
**F** 8 8 17
-------------------
> pander(f)
----- ----- --- --- ---
"Col" "A" "B" "C"
"Row"
"D" 15 9 7
"E" 13 14 9
"F" 8 8 17
----- ----- --- --- ---
如果要生成旧的rmarkdown
型管道表,请添加stlye='rmarkdown'
参数,尽管AFAIK Pandoc也是其中的新标准,它支持上述多行表.
If you want to generate the old rmarkdown
-style pipe tables, add stlye='rmarkdown'
parameter, although AFAIK Pandoc is the new standard there as well, which supports the above multi-line table.
这篇关于在Knitr中打印漂亮的交叉表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!