我想知道是否有任何函数可以很容易地在RStudio的查看器窗格中可视化html对象.例如,我想知道是否可以在查看器窗格中查看html表.
library("Quandl")
library("knitr")
df <- Quandl("FBI_UCR/USCRIME_TYPE_VIOLENTCRIMERATE")
kable(head(df[,1:9]), format = 'html', table.attr = "class=nofluid")
Run Code Online (Sandbox Code Playgroud)
mzu*_*uba 15
我有一个适用于 kable 表的解决方案。
kable(iris) %>% kableExtra::kable_styling()
Run Code Online (Sandbox Code Playgroud)
这会自动显示在查看器窗格中。不需要临时文件。
我最近在Gmisc-package中的htmlTable()函数中添加了这个功能,而且函数非常简单:
print.htmlTable<- function(x, useViewer = TRUE, ...){
# Don't use viewer if in knitr
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)
}
}
Run Code Online (Sandbox Code Playgroud)
RStudio 建议您使用getOption("viewer")而不是@ Ramnath的建议,即原始RStudio :: viewer().我的解决方案还添加了utils :: browserURL(),以防你不使用RStudio.我从这篇博文中得到了这个想法.
这是在RStudio中执行此操作的快速方法
view_kable <- function(x, ...){
tab <- paste(capture.output(kable(x, ...)), collapse = '\n')
tf <- tempfile(fileext = ".html")
writeLines(tab, tf)
rstudio::viewer(tf)
}
view_kable(head(df[,1:9]), format = 'html', table.attr = "class=nofluid")
Run Code Online (Sandbox Code Playgroud)
如果kable函数可以返回类的对象kable,则可以重命名,view_kable因为print.kable在这种情况下仅调用kable函数将在查看器中打开表.如果您认为这很有用,请继续在knitrgithub页面上提交功能请求.