R save FlexTable as html file in script

2019-08-17 05:49发布

问题:

I have a FlexTable produced with the ReporteRs package which I would like to export as .html.

When I print the table to the viewer in RStudio I can do this by clicking on 'Export' and selecting 'Save as webpage'.

How would I replicate this action in my script?

I don't want to knit to a html document or produce a report just yet as at present I just want separate files for each of my draft tables which I can share with collaborators (but nicely formatted so they are easy to read).

I have tried the as.html function and that does produce a .html file but all the formatting is missing (it is just plain text).

Here is a MWE:

# load libraries:
library(data.table)
library(ReporteRs)
library(rtable)

# Create dummy table:
mydt <- data.table(id = c(1,2,3), name = c("a", "b", "c"), fruit = c("apple", "orange", "banana"))

# Convert to FlexTable:
myflex <- vanilla.table(mydt)

# Attempt to export to html in script:
sink('MyFlexTable.html')
print(as.html(myflex))
sink()

# Alternately:
sink('MyFlexTable.html')
knit_print(myflex)
sink()

The problem with both methods demonstrated above is that they output the table without any formatting (no borders etc).

However, manually selecting 'export' and 'save as webpage' in RStudio renders the FlexTable to a html file with full formatting. Why is this?

回答1:

This works for me:

writeLines(as.html(myflex), "MyFlexTable.html")