{{}} 双大括号如何在 dplyr 中工作? [英] How do {{}} double curly brackets work in dplyr?

查看:33
本文介绍了{{}} 双大括号如何在 dplyr 中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 RConf 上看到了 Hadley 的演讲,他提到使用双括号在 tidy evals 中调用变量.

I saw Hadley's talk at RConf and he mentioned using double brackets for calling variables in tidy evals.

我搜索了谷歌,但找不到任何关于何时使用它们的信息.

I searched Google but I couldn't find anything talking about when to use them.

dplyr 中双括号的用例是什么?

What's the use case for double brackets in dplyr?

推荐答案

{{}} (curly-curly) 有很多应用.它被称为元编程,用于编写函数.例如,考虑这个例子:

{{}} (curly-curly) have lot of applications. It is called as meta-programming and is used for writing functions. For example, consider this example :

library(dplyr)
library(rlang)

mtcars %>% group_by(cyl) %>% summarise(new_mpg = mean(mpg))

# A tibble: 3 x 2
#    cyl new_mpg
#  <dbl>   <dbl>
#1     4    26.7
#2     6    19.7
#3     8    15.1

现在如果你想把它写成一个传递不带引号的变量(不是字符串)的函数,你可以使用 {{}} as :

Now if you want to write this as a function passing unquoted variables (not a string), you can use {{}} as :

my_fun <- function(data, group_col, col, new_col) {
  data %>%
    group_by({{group_col}}) %>%
    summarise({{new_col}} := mean({{col}}))
}

mtcars %>% my_fun(cyl, mpg, new_mpg)

#    cyl new_mpg
#  <dbl>   <dbl>
#1     4    26.7
#2     6    19.7
#3     8    15.1

请注意,您正在传递所有不带引号的变量和组列 (cyl)、正在聚合的列 (mpg)、新的名称列 (new_mpg) 都是动态的.这只是它的一个用例.

Notice that you are passing all the variables without quotes and the group-column (cyl), the column which is being aggregated (mpg), the name of new column (new_mpg) are all dynamic. This would just be one use-case of it.

要了解更多信息,请参阅:

To learn more refer to:

这篇关于{{}} 双大括号如何在 dplyr 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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