强制rstudio使用浏览器而不是查看器

时间:2015-10-23 23:31:38

标签: r rstudio

考虑一个函数(对于rstudio)将在查看器中打开y = TRUE,在浏览器中打开y = FALSE。您可以通过whatever强制options(viewer = NULL)在浏览器中打开(然后您需要重置为之前),但我无法使用正常{{1方法。在Windows和osx上测试。

on.exit

看起来观众并不尊重我在功能环境中的选项,只需要一些html(f <- function(x, y = TRUE) { if (y) { oo <- getOption('viewer') on.exit(options(viewer = oo)) options(viewer = NULL) } else options(viewer = NULL) print(getOption('viewer')) DT::datatable(x) } g <- function(x, y = TRUE) { if (y) { oo <- getOption('viewer') on.exit(options(viewer = oo)) options(viewer = NULL) } else options(viewer = NULL) print(getOption('viewer')) htmlTable::htmlTable(x) } ## in rstudio, returns the viewer function getOption('viewer') # function (url, height = NULL) # ... ## opens in viewer despite `options(viewer = NULL)` g(mtcars) # NULL ## again returns the function, ie, reset my options to before g call successfully getOption('viewer') # function (url, height = NULL) # ... ## opens in browser but leaves `options(viewer = NULL)` after exiting g(mtcars, FALSE) # NULL getOption('viewer') # NULL )或一个小部件(g)。我认为两者都会在函数中使用f并按退出时的方式返回我的选项,以便我可以控制我想要查看结果的位置。

或者有更好的方法为html和小部件执行此操作吗?我在viewer = NULL中尝试options参数无济于事,但这对DT::datatable案例没有帮助。

我能想到的唯一其他方法是将所有代码写入临时文件并使用htmlTable::htmlTable,我认为这对于看似如此简单的事情有很多工作要做。

2 个答案:

答案 0 :(得分:9)

虽然这不是解决方法,但我认为它说明了正在发生的事情。尝试在Sys.sleep()处理程序中添加on.exit()调用:

f <- function(x) {
  viewer <- getOption("viewer")
  on.exit({
    print("Restoring viewer...")
    Sys.sleep(3)
    options(viewer = viewer)
  }, add = TRUE)
  options(viewer = NULL)
  DT::datatable(x)
}

## opens in viewer despite `options(viewer = NULL)`
f(mtcars)

您会注意到,在<{1}}处理程序执行完毕后,之后<{1}}调用后才决定如何处理DT::datatable()调用。这意味着,当RStudio想要弄清楚结果时,观众已经恢复了!可能性是,RStudio会等到R不再“忙”来决定如何显示结果内容,然后暂时更改on.exit()选项。

请注意,这并不能解释viewer行为。我最好的猜测是存在某种竞争条件;丢失的htmlTable选项似乎会因策略性地放置viewer来电而消失......

不幸的是,解决这个问题意味着避免使用Sys.sleep()调用 - 当然,除非我们能够在RStudio中解决这个问题。

答案 1 :(得分:5)

通过将代码写入临时文件并使用browseURL或您喜欢的任何内容,您可以通过以下方式获得此功能。

fg的要点是相同的,所以你可以有一个函数来处理我想的任何类型的html代码或小部件。小部件可能需要selfcontained = TRUE

f <- function(x, y = TRUE) {
  x <- if ((inherits(x, 'iplot'))) x else DT::datatable(x)
  if (!y) {
    htmlFile <- tempfile(fileext = '.html')
    htmlwidgets::saveWidget(x, htmlFile, selfcontained = TRUE)
    utils::browseURL(htmlFile)
  } else x
}

g <- function(x, y = TRUE) {
  x <- htmlTable::htmlTable(x)
  if (!y) {
    htmlFile <- tempfile(fileext = '.html')
    writeLines(x, con = htmlFile)
    utils::browseURL(htmlFile)
  } else x
}

## opens in viewer
g(mtcars)
## opens in browser
g(mtcars, FALSE)

## same for widgets
f(mtcars)
f(mtcars, FALSE)

f(qtlcharts::iplot(1:5, 1:5), FALSE)

## and my options haven't changed
getOption('viewer')
# function (url, height = NULL) 
# ...

请注意,这实际上是使htmlTable::htmlTable使用其他查看器的正确方法,但g应适用于任何HTML。

library('htmlTable')
print(htmlTable(mtcars), useViewer = utils::browseURL)
相关问题