调整功能以使用dplyr/magrittr

joh*_*nes 2 r dplyr magrittr nse

我有:

df <- data_frame(
  a = 1:2, 
  b = list(1:10, 4:40)
)
Run Code Online (Sandbox Code Playgroud)

foo <- function(x) mean(unlist(x))
Run Code Online (Sandbox Code Playgroud)

以下按预期工作:

df$b %>% foo
Run Code Online (Sandbox Code Playgroud)

然而,我无法弄清楚哪些修改foo需要为了df %>% foo(b)工作.

ali*_*ire 6

您可以将...参数直接传递给vars帮助程序summarise_at,例如

foo <- function(.tbl, ...){
    summarise_at(.tbl, 
                 vars(...), 
                 funs(mean(unlist(.))))
}
Run Code Online (Sandbox Code Playgroud)

它适用于单个变量,列表列是否:

df %>% foo(b)
## # A tibble: 1 × 1
##          b
##      <dbl>
## 1 18.48936
Run Code Online (Sandbox Code Playgroud)

或多个:

df %>% foo(a, b)
## # A tibble: 1 × 2
##       a        b
##   <dbl>    <dbl>
## 1   1.5 18.48936
Run Code Online (Sandbox Code Playgroud)

要进一步了解NSE,请查看lazyeval,这是dplyr用来实现其NSE的包.

另请注意,dplyr的SE/NSE系统刚刚在开发版本中重建(尚未在CRAN上重建,尚未记录).


加分点:在R基础上做到这一切!

foo <- function(.tbl, ...){
    # collect dots as character vector
    cols <- as.character(substitute(list(...))[-1])
    cls <- class(.tbl)

    # handle grouped tibbles properly
    if('grouped_df' %in% cls){
        cls <- cls[which(cls != 'grouped_df')]    # drop grouping
        res <- aggregate(.tbl[cols], 
                         .tbl[attr(.tbl, 'vars')], 
                         FUN = function(x){mean(unlist(x))})
    } else {
        res <- as.data.frame(lapply(.tbl[cols], function(x){mean(unlist(x))}))
    }

    class(res) <- cls    # keep class (tibble, etc.)
    res
}
Run Code Online (Sandbox Code Playgroud)

它适用于列表列,组和多个列或组,保持类但丢弃分组:

df %>% foo(a, b)
## # A tibble: 1 × 2
##       a        b
##   <dbl>    <dbl>
## 1   1.5 18.48936

df %>% group_by(a) %>% foo(b)
## # A tibble: 2 × 2
##       a     b
##   <int> <dbl>
## 1     1   5.5
## 2     2  22.0

mtcars %>% foo(mpg, hp)
##        mpg       hp
## 1 20.09062 146.6875

mtcars %>% group_by(cyl, am) %>% foo(hp, mpg)
## # A tibble: 6 × 4
##     cyl    am        hp      mpg
##   <dbl> <dbl>     <dbl>    <dbl>
## 1     4     0  84.66667 22.90000
## 2     6     0 115.25000 19.12500
## 3     8     0 194.16667 15.05000
## 4     4     1  81.87500 28.07500
## 5     6     1 131.66667 20.56667
## 6     8     1 299.50000 15.40000
Run Code Online (Sandbox Code Playgroud)

  • 关于doc:[here](https://github.com/hadley/dplyr/blob/master/vignettes/nse.Rmd)他们说:看看`vignette("编程")`但我似乎无法找到它.他们显然是从'lazyeval`迁移到`rlang`但是`rlang`还没有亮点.我想我们会更快地知道 (2认同)
  • 我很不耐烦,但我想我可以再等一会儿,如果这意味着摆脱`.dots` (2认同)