R Prompt User With Autocomplete

无人久伴 提交于 2019-12-21 19:44:43

问题


Is there a way in R to prompt a user (i.e. scanf) for information and also allow auto-completion of that prompt using an array of strings as possible completions?

Basically, looking for something like GNU Readline for R (ideally with an example).


回答1:


The autocomplete for function names, etc., seems to be a property of the development environment that is running R. So it works slightly differently in R GUI compared to eclipse compared to emacs compared to RStudio compared to whatever.

From that, I think you may struggle to get autocomplete working in a portable way for scanf/readline without substantial hackery.

A better solution would be to create your own GUI, where you control the behaviour. Here's an example using gWidgets, with a dropdown list (aka combobox) whose choices reduce depending upon what is typed into it.

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)]
})

Inside that handler, h$obj refers to the dropdown list widget, svalue(h$obj) is the currently selected value and h$obj[] is the set of items.


The autocompletion in R GUI (and possibly others) is built upon a set of functions in the utils package (see ?rcompgen). Digging through the source of that may be useful, but I still think it will be hard to get it working while you are retrieving user input, in a way that is portable between development enivronments. (I'd be happy to be proved wrong though.)



来源:https://stackoverflow.com/questions/9003349/r-prompt-user-with-autocomplete

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!