Exporting R tables to HTML

Viewed 29112

Is there a way to easily export R tables to a simple HTML page?

5 Answers

The grammar of tables package gt is also an option.

Here's the example from the docs for generating a HTML table:

library(gt)

tab_html <-
  gtcars %>%
  dplyr::select(mfr, model, msrp) %>%
  dplyr::slice(1:5) %>%
  gt() %>%
  tab_header(
    title = md("Data listing from **gtcars**"),
    subtitle = md("`gtcars` is an R dataset")
  ) %>%
  as_raw_html()

In an issue for the DT package, someone posted how to use the DT package to get html in tables. I've pasted the relevant example code, modifying it to reference all columns with: targets = "_all".

library(DT)

render <- c(
  "function(data, type, row){",
  "  if(type === 'sort'){",
  "    var parser = new DOMParser();",
  "    var doc = parser.parseFromString(data, 'text/html');",
  "    data = doc.querySelector('a').innerText;",
  "  }",
  "  return data;",
  "}"
)

dat <- data.frame(
  a = c("AAA", "BBB", "CCC"), 
  b = c(
    '<a href="#" id = "Z" onclick = "Ztest">aaaaa</a>', 
    '<a href="#" id = "A" onclick = "Atest">bbbbb</a>',
    '<a href="#" id = "J" onclick = "Jtest">jjjjj</a>'
  )
)

datatable(
  dat, 
  escape = FALSE,
  options = list(
    columnDefs = list(
      list(targets = "_all", render = JS(render))
    )
  )
)

I hope this helps.

Related