Search code examples
rvariablesselection

Is autocompletion possible for udf? As in tidyverse: user types in first letters and selection menu appears


See this example where dplyr does autocompletion:

typeahead

I just typed my_ and a select menu appears including objects beginging with my_ inside the global environment and inside of df. On the other hand, see what happens if I type same first letters inside my own function my_fun`:

typeahead does not work

As you can see, here only the my_fun from the global environment appears in the list but the two variable names from df are missing! Can we do the autocompletion list as in the first screenshot for a user defined function?


Code. But keep in mind that this selection menu does not appear if you copy paste the first letters my_ - you have to actually type in my_ and then the menu appears.

df <- data.frame(my_var1= 1:5, my_var2= 6:10)
my_fun <- function(data, var){mean(data[ , var])}
df %>% mutate(my_)
my_fun(data= df, var= my_)

Edit: I want it to be "live", so the menu selection appears right after the first letters, i.e. user does not need to run code.

What I got so far: Here we see that we can use attach for autocompletion. So if we use attach(df) first, the variable names of df appear in the list. But for this user must run code in advance, i.e. it is not "live" as in first screenshot.


Solution

  • Note how you are using the magrittr pipe with mutate but not with my_fun. You will need to use the pipe operator to trigger data-variables to appear in the autocomplete menu:

    No data-variables in autocomplete:

    enter image description here

    data-variables in autocomplete

    enter image description here