!!! specification within select()

Hello,

So I was curious to what exactly "!!" and "!!!" does in the next bit of code. It helps me get the list object into the right format for the select function but I would like to know what is technically happening (I did check in Advanced R as well)


## Only run examples in interactive R sessions
if (interactive()) {

library(ggplot2)

# single selection
shinyApp(
  ui = fluidPage(
    varSelectInput("variable", "Variable:", mtcars),
    plotOutput("data")
  ),
  server = function(input, output) {
    output$data <- renderPlot({
      ggplot(mtcars, aes(!!input$variable)) + geom_histogram()
    })
  }
)


# multiple selections
## Not run: 
shinyApp(
 ui = fluidPage(
   varSelectInput("variables", "Variable:", mtcars, multiple = TRUE),
   tableOutput("data")
 ),
 server = function(input, output) {
   output$data <- renderTable({
      if (length(input$variables) == 0) return(mtcars)
      mtcars %>% dplyr::select(!!!input$variables)
   }, rownames = TRUE)
 }
)
## End(Not run)

}

Hi,

THe !! is called the bang-bang operator and is part of Tidyeval. This is part of the Tidyverse and in short ensures that you can make R interpret pieces of code like literal text, variables or executable code.

It's very powerful once you get the hang of it, but has a very steep learning curve in my opinion. I did start with it myself, but still don't get it all :slight_smile: I suggest you watch this great video on the topic which helped me out a lot:

In this specific case, the !! is needed to force ggplot (part of tidyverse) to evaluate the content of the input$variable and not the text itself. Normally in aes() you write the column name of interest without quotations, e.g. aes(x = mpg). If you don't use the !!, ggplot will see this: aes(x = input$variable) and starts looking for the column in the data with the name 'input$variable' which of course is not going to work. The !! transforms the code during evaluation into aes(x = mpg) if input$variable = mpg (so it uses the content instead of the name itself)

Hope this helps,
PJ

2 Likes

To complete @pieterjanvc answers, and to point to the correct chapters in NEW advanced R book you'll find informations in

Is this version of advanced R you read ?

3 Likes

This helps a lot! Thanks so much :slight_smile:

1 Like

Thanks for the link! I can see why you say it is quite complex :slight_smile:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.