dplyr-0.6.0编程unquoting

时间:2017-05-26 13:19:56

标签: r dplyr nse

我正在尝试用任意组编写一个简单的包装器来summarise()任意变量,并且现在已经取得了进展我已经得到了correct library version loaded但是又被混淆了(再次)关于如何取消引用多个值。

我目前有以下功能...

table_summary <- function(df     = .,
                          id     = individual_id,
                          select = c(),
                          group  = site,
                          ...){
    ## Quote all arguments (see http://dplyr.tidyverse.org/articles/programming.html)
    quo_id     <- enquo(id)
    quo_select <- enquo(select)
    quo_group  <- enquo(group)
    ## Subset the data
    df <- df %>%
          dplyr::select(!!quo_id, !!quo_select, !!quo_group) %>%
          unique()
    ## gather() data, just in case there is > 1 variable selected to be summarised
    df <- df %>%
          gather(key = variable, value = value, !!quo_select)
    ## Summarise selected variables by specified groups
    results <- df %>%
           group_by(!!quo_group, variable) %>%
           summarise(n    = n(),
                     mean = mean(value, na.rm = TRUE))
    return(results)
}

如果我指定一个分组变量,那么大部分都可以使用并且有效...

> table_summary(df = mtcars, id = model, select = c(mpg), group = gear)
# A tibble: 3 x 4
# Groups:   c(gear) [?]
       gear variable     n     mean
      <dbl>    <chr> <int>    <dbl>
1         3      mpg    15 16.10667
2         4      mpg    12 24.53333
3         5      mpg     5 21.38000

...但是当我指定多个group_by(!!quo_group, variable) ...

时,group = c(gear, hp)失败了
> mtcars$model <- rownames(mtcars)
> table_summary(df = mtcars, id = model, select = c(mpg), group = c(gear, hp))
Error in mutate_impl(.data, dots) : 
  Column `c(gear, hp)` must be length 32 (the group size) or one, not 64

我回去重新阅读了programming dplyr documentation,并且我读到你可以capture multiple variables使用quos()代替enquo()然后unquote-splice them with !!!,所以尝试了...

table_summary <- function(df     = .,
                          id     = individual_id,
                          select = c(),
                          group  = c(),
                          digits = 3,
                          ...){
    ## Quote all arguments (see http://dplyr.tidyverse.org/articles/programming.html)
    quo_id     <- enquo(id)
    quo_select <- enquo(select)
    quo_group  <- quos(group)  ## Use quos() rather than enquo()
    UQS(quo_group) %>% print() ## Check to see what quo_group holds
    ## Subset the data
    df <- df %>%
          dplyr::select(!!quo_id, !!quo_select, !!!quo_group)) %>%
          unique()
    ## gather() data, just in case there is > 1 variable selected to be summarised
    df <- df %>%
          gather(key = variable, value = value, !!quo_select)
    ## Summarise selected variables by specified groups
    results <- df %>%
               group_by(!!!quo_group, variable) %>%
               summarise(n    = n(),
                         mean = mean(value, na.rm = TRUE))
    return(results)
}

...现在在第一次引用!!!quo_group``within dplyr :: select()regardless of how many variables are specified under group =`...

时失败
> table_summary(df = mtcars, id = model, select = c(mpg), group = c(gear))
[[1]]
<quosure: frame>
~group

attr(,"class")
[1] "quosures"
Error in overscope_eval_next(overscope, expr) : object 'gear' not found
> traceback()
17: .Call(rlang_eval, f_rhs(quo), overscope)
16: overscope_eval_next(overscope, expr)
15: FUN(X[[i]], ...)
14: lapply(.x, .f, ...)
13: map(.x[matches], .f, ...)
12: map_if(ind_list, !is_helper, eval_tidy, data = names_list)
11: select_vars(names(.data), !(!(!quos(...))))
10: select.data.frame(., !(!quo_id), !(!quo_select), !(!(!quo_group)))
9: dplyr::select(., !(!quo_id), !(!quo_select), !(!(!quo_group)))
8: function_list[[i]](value)
7: freduce(value, `_function_list`)
6: `_fseq`(`_lhs`)
5: eval(quote(`_fseq`(`_lhs`)), env, env)
4: eval(quote(`_fseq`(`_lhs`)), env, env)
3: withVisible(eval(quote(`_fseq`(`_lhs`)), env, env))
2: df %>% dplyr::select(!(!quo_id), !(!quo_select), !(!(!quo_group))) %>% 
       unique()
1: table_summary(df = mtcars, id = model, select = c(mpg), group = c(gear))

看起来很奇怪,我认为问题的根源在于!!!quo_group(即UQS(quo_group))打印出~gear而不是添加print()的排序列表进入工作的例子显示发生...

> my_summarise <- function(df, ...) {
    group_by <- quos(...)
    UQS(group_by) %>% print()
    df %>%
    group_by(!!!group_by) %>%
    summarise(a = mean(a))
  }
> df <- tibble(
    g1 = c(1, 1, 2, 2, 2),
    g2 = c(1, 2, 1, 2, 1),
    a = sample(5), 
    b = sample(5)
  )
> my_summarise(df, g1, g2)
[[1]]
<quosure: global>
~g1

[[2]]
<quosure: global>
~g2

attr(,"class")
[1] "quosures"
# A tibble: 4 x 3
# Groups:   g1 [?]
     g1    g2     a
  <dbl> <dbl> <dbl>
1     1     1   1.0
2     1     2   5.0
3     2     1   2.5
4     2     2   4.0

我想明确地提供我想要分组的变量作为我的参数的参数但如果我将它们指定为...它是否有效但我决定在提供分组时测试我的函数是否有效变量为...

table_summary <- function(df     = .,
                          id     = individual_id,
                          select = c(),
                          group  = c(),
                          digits = 3,
                          ...){
    ## Quote all arguments (see http://dplyr.tidyverse.org/articles/programming.html)
    quo_id     <- enquo(id)
    quo_select <- enquo(select)
    ## quo_group  <- quos(group)
    quo_group  <- quos(...)
    UQS(quo_group) %>% print()
    ## Subset the data
    df <- df %>%
          dplyr::select(!!quo_id, !!quo_select, !!!quo_group) %>%
          unique()
    ## gather() data, just in case there is > 1 variable selected to be summarised
    df <- df %>%
          gather(key = variable, value = value, !!quo_select)
    ## Summarise selected variables by specified groups
    results <- df %>%
               group_by(!!!quo_group, variable) %>%
               summarise(n    = n(),
                         mean = mean(value, na.rm = TRUE))
    return(results)
}

...但它不会,quos()再次对#{1}}进行非引号拼接,因此变量既不会被选中也不会被...分组...

NULL

我已经多次完成这个循环,现在检查使用> table_summary(df = mtcars, id = model, select = c(mpg), gear, hp) NULL # A tibble: 1 x 3 variable n mean <chr> <int> <dbl> 1 mpg 32 20.09062 > table_summary(df = mtcars, id = model, select = c(mpg), gear) NULL # A tibble: 1 x 3 variable n mean <chr> <int> <dbl> 1 mpg 32 20.09062 enquo()的每种方法,但无法看到我出错的地方,尽管多次阅读编程dplyr文档。 / p>

1 个答案:

答案 0 :(得分:4)

IIUC你的帖子,你想提供c(col1, col2)group_by()。这个动词不支持这个:

group_by(mtcars, c(cyl, am))
#> Error in mutate_impl(.data, dots) :
#>   Column `c(cyl, am)` must be length 32 (the number of rows) or one, not 64

那是因为group_by()具有 mutate 语义,而不是选择语义。这意味着您提供给group_by()的表达式是变换表达式。这是一个令人惊讶但非常方便的功能。例如,您可以将disp分组为三个区间,如下所示:

group_by(mtcars, cut3 = cut(disp, 3))

这也意味着如果你提供c(cyl, am),它会将两列连接在一起并返回一个长度为64的向量,而它的长度为32(行数)。

所以你的问题是你想要一个具有选择语义的group_by()包装器。使用dplyr::select_vars()很容易做到这一点,很快就会将其提取到新的tidyselect包中:

library("dplyr")

group_wrapper <- function(df, groups = rlang::chr()) {
  groups <- select_vars(tbl_vars(df), !! enquo(groups))
  group_by(df, !!! rlang::syms(groups))
}

或者你可以包装具有select语义的新group_by_at()动词:

group_wrapper <- function(df, groups = rlang::chr()) {
  group_by_at(df, vars(!! enquo(groups)))
}

让我们试一试:

group_wrapper(mtcars, c(disp, am))
#> # A tibble: 32 x 11
#> # Groups:   disp, am [27]
#>      mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
#>    <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#>  1  21.0     6   160   110  3.90  2.62  16.5     0     1     4     4
#> # ... with 22 more rows

此界面的优点是支持所有select()操作以选择要分组的列。

请注意,我使用rlang::chr()作为默认参数,因为c()返回NULL,选择函数不支持chr()(我们可能希望将来更改它)。不带参数调用的{{1}}返回长度为0的字符向量。

相关问题