2

I am looking for an easy way to have my function work with input the comes from Shiny (i.e. string input) or with typical interactive use that is Tidyverse functions enable with NSE. Without the need to duplicate my code to handle each case separately.

An example of usage:

library(dplyr)

flexible_input <- function(var){
  mtcars %>% 
    select(var)
}

# This works for NSE
nse_input <- function(var){
  mtcars %>% 
    select({{ var }})
}

# This works for shiny but now I am duplicated my code essentially
shiny_input <- function(var){
  mtcars %>% 
    select(.data[[var]])
}

flexible_input(mpg)
flexible_input('mpg')
student
  • 1,001
  • 2
  • 12
  • 24
  • What do you mean by `# This works for NSE` and `# This works for shiny` ? The function works based on the inputs passed and how you call it. It does not change it's behaviour if you are using it in shiny or anywhere else. – Ronak Shah Sep 25 '21 at 08:02
  • Shiny widgets pass the values as strings. So the function would work with strings. Whereas NSE works by passing the name of the variable without being quoted. So the function will work with that input. – student Sep 25 '21 at 12:29

1 Answers1

1

If we need flexible_input to take string and unquoted input, convert to symbol and evaluate (!!)

flexible_input <- function(var){
  mtcars %>% 
    dplyr::select(!! rlang::ensym(var))
}

-testing

> flexible_input(mpg) %>% head
                   mpg
Mazda RX4         21.0
Mazda RX4 Wag     21.0
Datsun 710        22.8
Hornet 4 Drive    21.4
Hornet Sportabout 18.7
Valiant           18.1
> flexible_input("mpg") %>% head
                   mpg
Mazda RX4         21.0
Mazda RX4 Wag     21.0
Datsun 710        22.8
Hornet 4 Drive    21.4
Hornet Sportabout 18.7
Valiant           18.1
akrun
  • 874,273
  • 37
  • 540
  • 662