复制 dplyr quote 和 enquote 示例

replicating dplyr quote and enquote examples

我很难复制 [dplyr.tidyverse.org]http://dplyr.tidyverse.org/articles/programming.html.
中的示例 这是我的代码和会话信息。我今天花了太多时间追寻错误的线索,并重新安装软件包。任何帮助是极大的赞赏。

library(dplyr)  

 df <- tibble(  
 g1 = c(1, 1, 2, 2, 2),
 g2 = c(1, 2, 1, 2, 1),
 a = sample(5), 
 b = sample(5)
)

my_summarise <- function(df, group_by) {
 group_by <- enquo(group_by)
 print(group_by)

 df %>%
  group_by_(!!group_by) %>%
  summarise(a = mean(a))
}

my_summarise(df, g1)  

这是我得到的错误:

Error in !group_by : invalid argument type  
Called from: compat_lazy_dots(.dots, caller_env(), ...)  

这是会话信息:

R version 3.4.0 (2017-04-21)  
Platform: x86_64-w64-mingw32/x64 (64-bit)  
Running under: Windows 7 x64 (build 7601) Service Pack 1  


Matrix products: default  

locale:  
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252   
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C                          

[5] LC_TIME=English_United States.1252    

attached base packages:  
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] dplyr_0.7.4.9000     lubridate_1.5.6      pander_0.6.0         
RevoUtilsMath_10.0.0

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.11     digest_0.6.9     withr_1.0.2      assertthat_0.2.0 
R6_2.2.0         magrittr_1.5    
 [7] git2r_0.18.0     httr_1.2.1       stringi_1.1.5    rlang_0.1.2.9000 
curl_2.6         bindrcpp_0.2    
[13] devtools_1.12.0  RevoUtils_10.0.4 tools_3.4.0      stringr_1.2.0    
glue_1.1.1       compiler_3.4.0    
[19] pkgconfig_2.0.1  memoise_1.1.0    bindr_0.1        knitr_1.16       
tibble_1.3.3     

以下适合我。 group_by_ 已弃用,因此请使用 group_by。顺便说一下,您使用 group_by 作为函数的参数名称。我认为这是个坏主意,因为 group_bydplyr 中定义的函数。您可能需要考虑更改此参数名称以避免混淆。

library(dplyr)  

df <- tibble(  
  g1 = c(1, 1, 2, 2, 2),
  g2 = c(1, 2, 1, 2, 1),
  a = sample(5), 
  b = sample(5)
)

my_summarise <- function(df, group_by) {
  group_by <- enquo(group_by)
  print(group_by)

  df %>%
    group_by(!!group_by) %>%
    summarise(a = mean(a))
}

my_summarise(df, g1) 
<quosure: global>
~g1
# A tibble: 2 x 2
     g1     a
  <dbl> <dbl>
1     1     3
2     2     3

我遇到了完全相同的问题,上面发布的代码 ycw 给出了 invalid argument type。它似乎只发生在我升级 dplyr 的会话中,一旦我开始一个新的会话,ycw 发布的代码就可以正常工作。