Insert HTML tables in knitr documents in R

邮差的信 提交于 2019-12-08 07:07:12

问题


I have a number of different HTML files that contain formatted tables which I would like to combine in a knitr report in R. Unfortunately, I have some issues in loading the HTML files into R and including the tables in my knitr report.

The HTML files were created using the "save as htm" function in MS Excel and the stargazer library. They display flawlessly in any browser. My code is:

```{r, echo=FALSE, return='asis'}
library(XML)
overview.html <- htmlParse("overview.htm")
print(overview.html)
```

When printing "overview html" in the console I get the correct html code. However, when kniting the report the output document does not contain my code and I get the following error:

Warning message:
XML content does not seem to be XML: 'overview.htm' 

I have tried several variations of the above (using htmlTreeParse, using the print type = "html" option etc.) to no avail. It would be great if someone could suggest a way how this might work.


回答1:


If you want to preserve the formatting (and also not bother with XML/HTML churning), you can use an <iframe> to embed your full HTML document in the knitr doc like this:

```{r echo=FALSE, results='asis'}
tmp <- URLencode(paste(readLines("/path/to/table.htm"), collapse="\n"))

cat('<iframe src="data:text/html;charset=utf-8,', tmp ,
    '" style="border: none; seamless:seamless; width: 800px; height: 200px"></iframe>')
```

It won't show up in the RStudio viewer but it will show up in a real browser:

You'll need to tweak width and height (I could/should have made height a bit less for this example), but you'll have your fully formatted/styled tables in your knitted document this way.

NOTE: this only works if knitting to HTML.




回答2:


Here is my solution. Read the html into R and using xtable to output as html tables

```{r, echo=FALSE, return='asis'}
library(xtable)
u = "http://en.wikipedia.org/wiki/List_of_airlines_of_Malaysia"
tables = as.data.frame(readHTMLTable(u)[1])
print(xtable(tables),type='html',comment=FALSE)
```


来源:https://stackoverflow.com/questions/28189740/insert-html-tables-in-knitr-documents-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!