How to pass a named vector to dplyr::select using quosures?

后端 未结 1 1915
醉酒成梦
醉酒成梦 2020-12-10 15:26

Using the old select_() function, I could pass a named vector into select and change position and column names at once:

my_data  <- data_fram         


        
相关标签:
1条回答
  • 2020-12-10 15:49

    quo (or quos for multiple) is for unquoted variable names, not strings. To convert strings to quosures use sym (or syms), and use !! or !!! as appropriate to unquote or unquote-splice:

    library(dplyr)
    
    my_data  <- data_frame(foo = 0:10, bar = 10:20, meh = 20:30)
    my_newnames  <-  c("newbar" = "bar", "newfoo" = "foo")
    

    For strings,

    move_stuff_se <- function(df, ...){
         df %>% select(!!!rlang::syms(...))
    }
    
    move_stuff_se(my_data, my_newnames)
    #> # A tibble: 11 x 2
    #>    newbar newfoo
    #>     <int>  <int>
    #>  1     10      0
    #>  2     11      1
    #>  3     12      2
    #>  4     13      3
    #>  5     14      4
    #>  6     15      5
    #>  7     16      6
    #>  8     17      7
    #>  9     18      8
    #> 10     19      9
    #> 11     20     10
    

    For unquoted variable names,

    move_stuff_nse <- function(df, ...){
        df %>% select(!!!quos(...))
    }
    
    move_stuff_nse(my_data, newbar = bar, newfoo = foo)
    #> # A tibble: 11 x 2
    #>    newbar newfoo
    #>     <int>  <int>
    #>  1     10      0
    #>  2     11      1
    #>  3     12      2
    #>  4     13      3
    #>  5     14      4
    #>  6     15      5
    #>  7     16      6
    #>  8     17      7
    #>  9     18      8
    #> 10     19      9
    #> 11     20     10
    
    0 讨论(0)
提交回复
热议问题