Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R knitr print in a loop

Tags:

loops

r

knitr

I've been using the xtable package to create HTML tables out of R matrices. When I used the function kable in a loop, it didn't output anything. So I stared using the print function, which worked. The problem is that when I use the print function I get lots of "##" printed along the table HTML. Is there a way to print my kable but avoiding the "##" per line while in a loop?

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"')
like image 720
Flavia Amaral Avatar asked Feb 04 '15 04:02

Flavia Amaral


1 Answers

You should tell the chunk to use results as-is.

Do this by adding results='asis' to your chunk header.

Try this:

```{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"'))
}
```

You should get

speed    dist
4    2
4    10
7    4
7    22
8    16
9    10
like image 106
Andrie Avatar answered Oct 20 '22 05:10

Andrie