在RStudio查看器中查看标记生成的html
我想在RStudio查看器中查看使用在RStudio查看器中查看标记生成的html,r,r-markdown,R,R Markdown,我想在RStudio查看器中查看使用markdown生成的html文件,但是RStudio::viewer('test.html')在RStudio外部的浏览器中打开我的文件。你能告诉我怎样才能做到这一点吗 示例是有效的,但我不知道为什么我的示例不能以这种方式工作 test.htmlfile这是我们在选择new file->R Markdown时得到的一个符合要求的示例 编辑(根据Roman Luštrik的评论) 库(knitr) 图书馆(降价) 如前所述,键使用的是tempfile()。只要
markdown
生成的html
文件,但是RStudio::viewer('test.html')
在RStudio外部的浏览器中打开我的文件。你能告诉我怎样才能做到这一点吗
示例是有效的,但我不知道为什么我的示例不能以这种方式工作
test.html
file这是我们在选择new file->R Markdown时得到的一个符合要求的示例
编辑(根据Roman Luštrik的评论)
库(knitr)
图书馆(降价)
如前所述,键使用的是tempfile()
。只要html文件在会话临时目录之外,Rstudio就不会显示它
另一方面,这将起作用:
temp.f <- tempfile()
cat("Hello", file = temp.f)
rstudio::viewer(temp.f)
在我的RStudio版本(0.98.994)中,单击“knit HTML”按钮右侧的小向下箭头,可以选择“在窗格中查看”和“在窗口中查看”。选择第一个而不是第二个为我修复了它。通过修改此处给出的响应,可以找到一个很好的综合解决方案:
或者,为了方便起见,我在最后复制了完整的代码
具体而言,通过以下三个简单步骤修改print.htmlTable的定义:
(1)在函数声明中添加如下标志:
print.htmlTable<- function(x, useViewer = TRUE, as.file.path = FALSE, ...)
if(as.file.path){ x <- read_file(x)}
view.htmlFile <- function(x, ...){
print.htmlTable(x, useViewer = TRUE, as.file.path = TRUE, ...)
}
提醒:这是对由编写的原始函数的调整/修改。相应地给予信用
print.htmltable您可以发布一个小的、可复制的、不适合您的示例吗?好的,这里的示例取自knitr
,使用markdown
package生成的html,它可能与当前版本不同。改用rstudioapi::viewer(…)
。
if(as.file.path){ x <- read_file(x)}
view.htmlFile <- function(x, ...){
print.htmlTable(x, useViewer = TRUE, as.file.path = TRUE, ...)
}
view.htmlFile(filepath.to.html) #i.e. 'knitr-minimal.html' or any other html file
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)