R中有没有办法提示用户(即scanf)获取信息,并且还允许使用字符串数组作为可能的完成来自动完成该提示?
基本上,寻找类似 GNU Readline for R 的东西(最好有一个例子)。
函数名称等的自动完成似乎是运行 R 的开发环境的一个属性。因此,与 eclipse 相比,emacs 与 RStudio 相比,它在 R GUI 中的工作方式略有不同。
从那以后,我认为您可能很难让自动完成功能以便携的方式工作,scanf
而readline
无需大量黑客攻击。
更好的解决方案是创建您自己的 GUI,您可以在其中控制行为。这是一个使用 , 的示例gWidgets
,带有一个下拉列表(又名组合框),其选择会根据输入的内容而减少。
library(gWidgetstcltk) # or gWidgetsRGtk2, etc.
#some choices to complete to
choices <- c("football", "barometer", "bazooka")
#sort to make it easier for the user to find one, and
#prepend with a blank string to type in
items <- c("", sort(choices))
#create a gui
win <- gwindow()
drp <- gdroplist(items = items, editable = TRUE, cont = win)
#When the user types something, update the list of available items
#to those that begin with what has been typed.
addHandlerKeystroke(drp, handler = function(h, ...)
{
regex <- paste("^", svalue(h$obj), sep = "")
h$obj[] <- items[grepl(regex, items)]
})
在该处理程序内部,h$obj
指的是下拉列表小部件,svalue(h$obj)
是当前选定的值并且h$obj[]
是项目集。
R GUI(可能还有其他)中的自动完成功能基于utils
包中的一组函数(请参阅 参考资料?rcompgen
)。挖掘其来源可能很有用,但我仍然认为在检索用户输入时很难让它工作,以一种在开发环境之间可移植的方式。(不过,我很高兴被证明是错误的。)
你可以用 rstudioapi 来做这件事
choices = list(test=\(){cat("test")})
rstudioapi::sendToConsole("choices$",execute = F)
按下选项卡现在具有运行相关功能的自动完成选项。