Search code examples
rshinynse

R function that works with NSE and Shiny Inputs


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

Solution

  • 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