How to make Shiny's input$var consumable for dplyr::summarise()

前端 未结 1 1492
旧时难觅i
旧时难觅i 2020-12-19 19:44

I have the following Rmarkdown Shiny:

---
title: \"My Title\"
runtime: shiny
output: 
  flexdashboard::flex_dashboard:
    vertical_layout:          


        
相关标签:
1条回答
  • 2020-12-19 20:40

    Using the development version of dplyr (v0.5.0.9002) you could turn your string into a symbol using rlang::sym() and then use the unquote operator (!! or UQ) to refer to the variable in the dplyr verbs.

    library(dplyr)
    
    var1 <- "Good" # replace with input$op_id
    var2 <- rlang::sym("price") # replace with input$col_id
    
    diamonds %>%
      filter(cut == var1) %>%
      select_at(vars(!!var2)) %>%
      summarise_at(vars(!!var2), funs(mean, sd, n()))
    

    Which gives:

    ## A tibble: 1 × 3
    #      mean      sd     n
    #     <dbl>   <dbl> <int>
    #1 3928.864 3681.59  4906
    

    Should you have more than one variable, use rlang::syms() with the unquote splice operator (!!! or UQS). For example:

    var1 <- "Good" 
    var2 <- rlang::syms(c("price", "depth")) 
    
    diamonds %>%
      filter(cut == var1) %>%
      select_at(vars(UQS(var2))) %>%
      summarise_at(vars(UQS(var2)), funs(mean, sd, n()))
    

    Which gives:

    ## A tibble: 1 × 6
    #  price_mean depth_mean price_sd depth_sd price_n depth_n
    #       <dbl>      <dbl>    <dbl>    <dbl>   <int>   <int>
    #1   3928.864   62.36588  3681.59 2.169374    4906    4906
    

    For more information, have a look at the quasiquotation section of the Programming with dplyr vignette

    0 讨论(0)
提交回复
热议问题