如何使用 quosures 将命名向量传递给 dplyr::select? [英] How to pass a named vector to dplyr::select using quosures?

查看:12
本文介绍了如何使用 quosures 将命名向量传递给 dplyr::select?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用旧的 select_() 函数,我可以将命名向量传递给 select 并立即更改位置和列名称:

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

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

move_stuff  <- function(df, newnames) {
    select_(df, .dots = newnames)
}

move_stuff(my_data,  newnames = my_newnames) )

# this is the desired output
# A tibble: 4 x 2
  newbar  newfoo
   <int>   <int>
1     10       0
2     11       1
3     12       2
4     13       3

我尝试使用 quosures 和 splicing 做类似的事情——选择列效果很好,但向量的名称(因此同时重命名列)似乎被忽略了.以下两个返回数据帧的列名为 barfoo,但不返回 newbarnewfoo:>

I tried doing something similar using quosures and splicing--selecting columns works great, but the names of the vectors (and thus renaming columns at the same time) seems to be ignored. Both of the following return data frames with columns named bar and foo, but not newbar and newfoo:

move_stuff2  <- function(df, newnames) {
  select(df, !!!newnames)
}

# returns df with columns bar and foo
move_stuff2(my_data, quo(my_newnames))
move_stuff2(my_data, quos(my_newnames))

有没有办法使用新的 NSE 方法使用命名向量来重命名和重新排序列?

Is there a way to use a named vector using the new NSE methodology to both rename and reorder columns?

推荐答案

quo(或 quos 表示多个)用于不带引号的变量名,而不是字符串.要将字符串转换为 quosures 使用 sym(或 syms),并根据需要使用 !!!!!取消引用或取消引用拼接:

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")

对于字符串,

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

这篇关于如何使用 quosures 将命名向量传递给 dplyr::select?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆