Is it possible to view an HTML table in the viewer

2019-04-08 07:45发布

问题:

I would like to know if there is any function which makes it easy to visualize an html object in the RStudio's viewer pane. For instance, I would like to know if it would be possible to view an html table in the viewer pane.

library("Quandl")
library("knitr")
df  <-  Quandl("FBI_UCR/USCRIME_TYPE_VIOLENTCRIMERATE")
kable(head(df[,1:9]), format = 'html', table.attr = "class=nofluid")

回答1:

Here is a quick way to do this in RStudio

view_kable <- function(x, ...){
  tab <- paste(capture.output(kable(x, ...)), collapse = '\n')
  tf <- tempfile(fileext = ".html")
  writeLines(tab, tf)
  rstudio::viewer(tf)
}
view_kable(head(df[,1:9]), format = 'html', table.attr = "class=nofluid")

If the kable function can return an object of class kable, then one could rename view_kable as print.kable in which case merely calling the kable function would open the table in the viewer. If you think this is useful, please go ahead and file a feature request on the knitr github page.



回答2:

I recently added this functionality to my htmlTable() function in the Gmisc-package and the function is rather simple:

print.htmlTable<- function(x, useViewer = TRUE, ...){
  # Don't use viewer if in knitr
  if (useViewer &&
        !"package:knitr" %in% search()){

    htmlFile <- tempfile(fileext=".html")
    htmlPage <- paste("<html>",
                      "<head>",
                      "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\">",
                      "</head>",
                      "<body>",
                      "<div style=\"margin: 0 auto; display: table; margin-top: 1em;\">",
                      x,
                      "</div>",
                      "</body>",
                      "</html>", sep="\n")
    cat(htmlPage, file=htmlFile)

    viewer <- getOption("viewer")
    if (!is.null(viewer) &&
          is.function(viewer)){
      # (code to write some content to the file)
      viewer(htmlFile)
    }else{
      utils::browseURL(htmlFile)
    }
  }else{
    cat(x)
  }
}

RStudio recommends that you use the getOption("viewer") instead of @Ramnath's suggestion, the raw RStudio::viewer(). My solution also adds the utils::browserURL() in case you are not using RStudio. I got the idea from this blog post.



回答3:

As was explained on this RStudio Support page, the key is to use tempfile() :

Note that the Viewer pane can only be used for local web content. This content can either be static HTML files written to the session temporary directory (i.e. files with paths generated by the tempfile function) or a locally run web application.

See my answer to this question for a bare-bones example.



标签: r rstudio