通过修改此处给出的响应,可以找到一个很好的综合解决方案:
Is it possible to view an HTML table in the viewer pane?或者,为了方便,我把完整的代码复制到了最后
具体来说,修改print.htmlTable的定义,简单三步:
(1)在函数声明中添加标志如下:
print.htmlTable<- function(x, useViewer = TRUE, as.file.path = FALSE, ...)
(2) 在函数定义中,添加以下行:
if(as.file.path){ x <- read_file(x)}
(3) 创建一个包装函数来查看文件:
view.htmlFile <- function(x, ...){
print.htmlTable(x, useViewer = TRUE, as.file.path = TRUE, ...)
}
(4) 现在,您可以使用包装器通过文件路径查看 HTML 文件
(以及查看未保存的 html 输出的原始功能):
view.htmlFile(filepath.to.html) #i.e. 'knitr-minimal.html' or any other html file
提醒:这是对Max Gordon 在earlier post 中编写的原始函数的调整/修改。相应地给予信用。
print.htmlTable<- function(x, useViewer = TRUE, as.file.path = FALSE, ...){
if(as.file.path){ x <- read_file(x)}
# Don't use viewer if knitr package is loaded (assumes if you loaded knitr, you are using knitr and dont want to use Viewer)
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)
}
}
#Wrapper to allow viewing of files using path
view.htmlFile <- function(x, ...){
print.htmlTable(x, useViewer = TRUE, as.file.path = TRUE, ...)
}
view.htmlFile(filepath.to.html)