Is there a way to easily export R tables to a simple HTML page?
The xtable
function in the xtable
package can export R tables to HTML tables. This blog entry describes how you can create HTML pages from Sweave documents.
It might be worth mentioning that there has been a new package specifically designed to convert (and style with css) data.frames (or tables) into HTML tables in an easy and intuitive way. It is called tableHTML
. You can see a simple example below:
library(tableHTML)
#create an html table
tableHTML(mtcars)
#and to export in a file
write_tableHTML(tableHTML(mtcars), file = 'myfile.html')
You can see a detailed tutorial here as well.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.