且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-11-18 18:36:00

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

Although this isn't a fix, I think it illustrates what's going on. Try adding a Sys.sleep() call in the on.exit() handler:

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)

您会注意到 RStudio 不会决定"如何处理 DT::datatable() 调用的结果,直到 after on.exit() 处理程序已完成执行.这意味着,当 RStudio 想要弄清楚如何处理结果时,查看器已经恢复了!奇怪的是,RStudio 会等到 R 不再忙"来决定如何显示结果内容,然后临时更改 viewer 选项为时已晚.

You'll notice that RStudio doesn't 'decide' what to do with the result of DT::datatable() call until after the on.exit() handler has finished execution. This means that, by the time RStudio wants to figure out to do with the result, the viewer has already been restored! Odds are, RStudio waits until R is no longer 'busy' to decide how to display the resulting content, and by then is too late for temporary changes to the viewer option.

请注意,这并不能解释 htmlTable 的行为.我***的猜测是存在某种竞争条件;丢失的 viewer 选项似乎随着战略性放置的 Sys.sleep() 调用而消失...

Note that this doesn't explain the htmlTable behaviour. My best guess is that there is some kind of race condition going on; the lost viewer option seems to go away with strategically placed Sys.sleep() calls...

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

Unfortunately, working around this means avoiding the use of on.exit() call -- unless we can figure out to handle this in RStudio, of course.