Unquoting Shiny Inputs for dplyr functions



I'm trying to use a shiny selectInput("sort_var", "Sort on..", choices = colnames(df)) value inside a dplyr pipe so the dataframe is sorted by the selected variable with arrange, but I'm struggling to follow the recommended tidyeval quoting and unquoting of inputs because the shiny input is already quoted and so the following code doesn't seem to work...

sorted_df <- reactive({
  sort <- quo(input$sort_var)
  df %>% 

The following code does what I'm looking for..

sorted_df <- reactive({
  df %>%
    arrange(.[[grep(paste0("^", input$sort_var, "$"), colnames(df))]])

But I'd be interested to know if there is a workable tidyeval procedure for this.



There's no need to unquote here. You can use arrange_at to pass the character vector.

input <- list(sort_var = "gear")

mtcars %>% 
  arrange_at(.vars = input$sort_var)


but of course! thanks a lot.

what about for use with the wt argument of top_n?

df %>%
  top_n(n = 10, wt = input$sort_var)


If I understand lazy evaluation correctly (very big, tenuous assumption), then quo is for taking expressions and quoting them (delaying evaluation), while sym intended to take characters and convert them to expressions (with delayed evaluation).

Since you start with a character in input$sort_var, I think what you're aiming for is


input <- list(sort_var = "mpg")

sorta <- rlang::sym(input$sort_var)

mtcars %>% 
  top_n(n = 2, wt = !!sorta)