Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom tab completion in R function

Tags:

autocomplete

r

I am currently writing a function which only accepts certain inputs (in the example only "a" and "b"). For all other inputs the function will return an error.

test <- function(x) {
  allowedX <- c("a","b")
  if(x %in% allowedX) print("Good choice!")
  else stop("wrong input!")
}

To help users of the function I would like to supply the allowed values for x (stored in allowedX) using the tab completion feature in R and replace the default file name completion which is typically applied after a quote. So pressing TAB should give something like:

test(x="<TAB>
a b

However, I couldn't find a solution so far how to map the vector allowedX to the tab completion in R. Can somebody tell me how to do that?

Thanks in advance!

like image 335
user2572255 Avatar asked Jul 11 '13 11:07

user2572255


People also ask

How do I display completions in RStudio?

Previously RStudio only displayed completions “on-demand” in response to the tab key. Now, RStudio will proactively display completions after a $ or :: as well as after a period of typing inactivity. All of this behavior is configurable via the new completion options panel:

Which functions expect package names for completions in R?

In addition, certain functions, such as library () and require (), expect package names for completions. RStudio automatically infers whether a particular function expects a package name and provides those names as completion results: Completion is now also S3 and S4 aware.

How do I use crosstab in R?

The crosstab function is not part of the built-in set of R code functions but it is available online for inclusion in projects. While you do have the option of copying and pasting the cross table function into your code you can also add it by the following command.

How does RStudio know what package a function expects?

RStudio automatically infers whether a particular function expects a package name and provides those names as completion results: Completion is now also S3 and S4 aware. If RStudio is able to determine which method a particular function call will be dispatched to it will attempt to retrieve completions from that method.


1 Answers

You could try something like the following:

test <- function() {
  allowedX <- c("a","b")
  x = readline('Please enter your choice of parameters (either "a" or "b"): ')
  if(x %in% allowedX) print("Good choice!")
  else stop("wrong input!")
}
like image 164
Ricardo Monti Avatar answered Sep 30 '22 13:09

Ricardo Monti