Search code examples
rexportcrosstab

Exporting html output to latex, .png or .doc


I am doin some cross tabulation with the sjPlot package that produces wonderful tables in HTML.

library(sjPlot)
iris<-iris
tab_xtab(iris$Species,iris$Sepal.Width,show.row.prc = TRUE,show.col.prc = TRUE)

While the output looks great in the consol, I would like to export it and put them in a report. Ideally, I would like to export them into a latex file, but also as a .png as a .doc file would be ok.

Does anyone know how I could do this?

thanks a lot for your help

Best


Solution

  • One option is to use webshot::webshot():

    library(sjPlot)
    library(webshot)
    
    # location to write html version to
    my_html <- tempfile(fileext = ".html")
    
    # write html to temp file
    tab_xtab(iris$Species,
             iris$Sepal.Width,
             show.row.prc = TRUE,
             show.col.prc = TRUE, 
             file = my_html)
    
    # location to write png version to
    my_png <- tempfile(fileext = ".png")
    
    # take a webshot of html and save to png
    webshot::webshot(my_html, my_png, vheight = 300)
    

    enter image description here

    Note, you will likely have to install PhantomJS after installing the webshot package. This can be done with webshot::install_phantomjs().

    You may also have to play around with the vwidth and vheight arguments to avoid extra white-space in your png.