Ben*_*Ben 40 r pandoc knitr r-markdown
如何在RMarkdown中手动简单地格式化表格,在转换为HTML(使用knitr和markdown包),PDF(使用pandoc和miktex)和docx(使用pandoc)时看起来很好?
我希望能够在RMarkdown中编写小表,这些表不是R函数的结果,这些函数在我最常使用的三种格式中看起来很好.到目前为止,我发现3种格式中有2种格式看起来不错,可能是3/3吗?
一.这在Knit HTML之后看起来不错,但在PDF或docx中并不好
<table>
<tr>
<td>Eggs</td>
<td>Ham</td>
</tr>
<tr>
<td>Basil</td>
<td>Tomato</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
二.这个在Knit HTML之后看起来不错,但在PDF或docx中并不好
| Tables | Are | Cool |
| ------------- |:-------------:| -----:|
| col 3 is | right-aligned | $1600 |
| col 2 is | centered | $12 |
| zebra stripes | are neat | $1 |
Run Code Online (Sandbox Code Playgroud)
三.这个在Knit HTML之后看起来不太好但是在PDF和docx中很好(到目前为止最好的选择)
V1 Tweedledee Tweedledum
-------- -------------- ----------------
Age 14 14
Height 3'2" 3'2"
Politics Conservative Conservative
Religion "New Age" Syrian Orthodox
--------- -------------- ----------------
Run Code Online (Sandbox Code Playgroud)
四.在编织HTML并制作PDF和docx(获胜者!)之后这看起来不错,但不是我之后的手动格式.
```{r table1, echo=FALSE, message=FALSE, warnings=FALSE, results='asis'}
require(pander)
panderOptions('table.split.table', Inf)
set.caption("Data on cars")
pander(mtcars, style = 'rmarkdown')
```
Run Code Online (Sandbox Code Playgroud)
这就是我制作PDF和docx文件的方式:
filen <- "table" # name of my RMarkdown file without suffix
knit(paste0(filen,".Rmd"))
# make PDF
system(paste0("pandoc -s ", paste0(filen,".md"), " -t latex -o ", paste0(filen,".pdf"), " --highlight-style=tango -S"))
# make docx
system(paste0("pandoc -s ", paste0(filen,".md"), " -o ", paste0(filen,".docx"), " --highlight-style=tango -S"))
Run Code Online (Sandbox Code Playgroud)
Ben*_*Ben 35
受到daroczig评论的启发,特别是pander转换为pandoc管道语法的线索,我仔细研究了pander文档并找到了参考文献cat.经过一些实验,我找到了胜利者:
```{r table2, echo=FALSE, message=FALSE, warnings=FALSE, results='asis'}
tabl <- " # simple table creation here
| Tables | Are | Cool |
|---------------|:-------------:|------:|
| col 3 is | right-aligned | $1600 |
| col 2 is | centered | $12 |
| zebra stripes | are neat | $1 |
"
cat(tabl) # output the table in a format good for HTML/PDF/docx conversion
```
Run Code Online (Sandbox Code Playgroud)
在我的测试中,这会在HTML,PDF和docx中生成一致好看的表.现在我要向其他一些问题提出问题,感谢他帮助我解决问题.
如果你需要一个表格的标题...那么你需要做一点不同的.请注意,标题只能在PDF中显示,而不能在HTML中显示:
```{r table-simple, echo=FALSE, message=FALSE, warnings=FALSE, results='asis'}
require(pander)
panderOptions('table.split.table', Inf)
set.caption("My great data")
my.data <- " # replace the text below with your table data
Tables | Are | Cool
col 3 is | right-aligned | $1600
col 2 is | centered | $12
zebra stripes | are neat | $1"
df <- read.delim(textConnection(my.data),header=FALSE,sep="|",strip.white=TRUE,stringsAsFactors=FALSE)
names(df) <- unname(as.list(df[1,])) # put headers on
df <- df[-1,] # remove first row
row.names(df)<-NULL
pander(df, style = 'rmarkdown')
```
Run Code Online (Sandbox Code Playgroud)