立即在 R 中显示帮助 (Rstudio)

Displaying help in R immediately (Rstudio)

我正在 R 中创建一个包,它将通过 tcltk 包提供一个 GUI 界面。前端函数将通过 GUI 从用户那里获取数据,并调用后端函数 returns 将结果返回给前端。我目前已经编写了所有功能的文档,除了这部分和一些错误测试外,功能也已完成。

为了帮助用户,我希望能够打印文档。在 Rstudio 中,它显示在帮助 window 中(重要的是要注意,这个 window 不是我的代码通过 tcltk 包创建的,这个 window 是 Rstudio 的一部分)。

如果我的功能仅通过命令行与用户交互,我可以让 Rstudio 中的帮助屏幕立即更新。但是,如果我正在使用图形,帮助 window 将在函数完成后才会更新,这违背了让它首先打印帮助屏幕的目的。

下面是通过 tcltk 包创建的 GUI window 示例。我在这里使用 var.test 作为示例文档,因此请确保您的帮助 window 在帮助屏幕更新时查看其他内容。

require(tcltk)
print(help(var.test))

hi <- tktoplevel() #creates a window

ok <- function() # this function is called by pushing the button defined below
{
  print("Goodbye, World!")
  tkdestroy(hi)    # destroys the window
}

print("Hello, World!")

ok.button <- ttkbutton(hi, text = "This is a button", command = ok) #defines the button
tkgrid(ok.button) #puts the button on the window "hi"

tkfocus(hi)

tkwait.window(hi)

如您所见,即使在创建 tcltk 图形 window 之前先调用帮助函数,也不会使帮助 window 更新。打印功能似乎仍然有效,因为在按下按钮之前打印了 "Hello, World"。

为了让我的功能正常运行,我必须使用tkwait.window(),否则前端将无法与后端同步。

如果让 Rstudio window 更新真的不可能,那么使用不同 window 或程序的替代解决方案是可以接受的。

尝试打印帮助后在您的代码中添加一个小延迟:

....
print(help(var.test))
# Sys.sleep(0.01)  # too short
Sys.sleep(0.5)   # long enough
...

这适用于 Linux 和 Windows...

我猜 RStudio 在执行 R 命令批处理(您一次发送给 R 的所有命令)时没有更新 GUI,因为它阻止更新在 "blocking sub thread" 中执行 R,因此表现得像 "single threading" 以便在 R 批处理的执行结束之前无法更新 GUI。

睡眠功能似乎 return 对 RStudio(GUI?)进程的控制,以便它可以更新 GUI。

如果您过多地减少休眠时间,您可以观察到 RStudio GUI 的部分更新。

PS:使用process.events()无效!