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).
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