Using pre-existing character vectors in quasi-quantizing an expression with rlang
Sometimes when working with dplyr
there is a character vector of column names that will be used to work with the data, for example:
cols_of_interest <- c("Petal.Width", "Petal.Length")
In dplyr
0.5.0 and earlier, the recommended approach to this problem was to use the underscore construct verb_
like this:
library("tidyverse")
my_cols <- c("Petal.Width", "Petal.Length")
iris %>%
select_(.dots = my_cols)
The functions are now verb_
deprecated in favor of the new clear scoring scheme (dplyr.tidyverse.org/articles/programming.html) provided by the library rlang
.
In accordance with dplyr
0.7.0 the following works without any special conditions:
library("tidyverse")
# library("rlang")
my_cols <- c("Petal.Width", "Petal.Length")
iris %>%
select(my_cols)
Note that dplyr
this was not the case on the development lines .
Motivation
Column selection in Shiny apps is a good use case as it can be done using the verb_
notation
library("shiny")
library("tidyverse")
library("DT")
shinyApp(
ui = fluidPage(
selectInput("cols_to_show",
"Columns to show",
choices = colnames(iris),
multiple = TRUE),
dataTableOutput("verb_table")
),
server = function(input, output){
output$verb_table <- renderDataTable({
iris %>%
select_(.dots = input$cols_to_show)
})
}
)
source to share
In pre 0.5.0, the dplyr
basic structure for non-standard evaluation was lazyeval
and required special consideration for strings. Hadley Wickham has released a groundbreaking version dplyr
with a new underbelly titled rlang
, which provides a more consistent structure for out-of-the-box assessment. It was version 0.70 - it explains why 0.6.0 was omitted here - https://blog.rstudio.org/2017/06/13/dplyr-0-7-0/
Below we work without special considerations:
library("tidyverse")
my_cols <- c("Petal.Width", "Petal.Length")
iris %>%
select(my_cols)
Note that the new structure rlang
adds the ability to have a vector of bare characters using quosures
my_quos <- quos(Petal.Width, Petal.Length)
iris %>%
select(!!!my_quos)
You can read more about programming with help dplyr
here - http://dplyr.tidyverse.org/articles/programming.html
Comparison in Shiny
library("shiny")
library("tidyverse")
library("DT")
library("rlang")
shinyApp(
ui = fluidPage(
selectInput(
"cols_to_show",
"Columns to show",
choices = colnames(iris),
multiple = TRUE
),
dataTableOutput("verb_table"),
dataTableOutput("tidyeval_table")
),
server = function(input, output) {
output$verb_table <- renderDataTable({
iris %>%
select_(.dots = input$cols_to_show)
})
output$tidyeval_table <- renderDataTable({
iris %>%
select(!!!syms(input$cols_to_show))
})
}
)
source to share