R knitr 循环打印

R knitr print in a loop

我一直在使用 xtable 包从 R 矩阵中创建 HTML tables。当我在循环中使用函数 kable 时,它没有输出任何内容。所以我开始使用 print 函数,它起作用了。问题是,当我使用打印功能时,我在 table HTML 上打印了很多“##”。有没有办法打印我的 kable 但在循环中避免每行“##”?

library("xtable", lib.loc="~/R/win-library/3.1")

for(i in 1:3) {
    #Must use print because of the loop, but get ## per line
    print(kable(head(cars), "html", table.attr='class="flat-table"'))
}
#No neded to use print, no ## printed per line
kable(head(cars), "html", table.attr='class="flat-table"')

您应该告诉块使用结果 as-is。

通过将 results='asis' 添加到您的区块 header 来完成此操作。

试试这个:

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

for(i in 1:3) {
  #Must use print because of the loop, but get ## per line
  print(kable(head(cars), "html", table.attr='class="flat-table"'))
}
```

你应该得到

speed    dist
4    2
4    10
7    4
7    22
8    16
9    10