什么是“拥抱运算符"?`{{}}`? [英] What is the "embracing operator" `{{ }}`?

查看:81
本文介绍了什么是“拥抱运算符"?`{{}}`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚遇到了拥抱运算符"{{ }}tidyverse 风格指南.

I just came across the "embracing operator" {{ }} in section 2.2.3 of the tidyverse style guide.

拥抱运算符 {{ }} 在 R 中有什么作用?

What does the embracing operator {{ }} do in R?

推荐答案

它叫做 curly-curly 运算符(参见?"{{}}").

在传递必须在其他上下文中进行评估之前就地替换的参数时,这很有用.

It's useful when passing an argument that has to be substituted in place before being evaluated in another context.

看这个简单的例子(虽然有点尴尬,因为我们可以在这里调用函数时简单地引用cyl"):

See this simple example (although a bit awkward as we could simple quote the "cyl" when calling the function here):

library(dplyr)

# does not work
get_var <- function(data, column) {
  data %>% select(column)
}

get_var(mtcars, cyl)
#> Error: object 'cyl' not found

# works
get_var <- function(data, column) {
  data %>% select({{ column }})
}

get_var(mtcars, cyl)
#>                     cyl
#> Mazda RX4             6
#> Mazda RX4 Wag         6
#> Datsun 710            4
#> Hornet 4 Drive        6
#> Hornet Sportabout     8
#> ...

reprex 包 (v0.3.0) 于 2020 年 7 月 8 日创建

Created on 2020-07-08 by the reprex package (v0.3.0)

或者一个更好的例子:

library(dplyr)

# does not work
get_var <- function(data, column, value) {
  data %>% filter(column == value)
}

get_var(mtcars, cyl, 6)
#> Error: Problem with `filter()` input `..1`.
#> x object 'cyl' not found
#> i Input `..1` is `column == value`.

# works
get_var <- function(data, column, value) {
  data %>% filter({{ column }} == value)
}

get_var(mtcars, cyl, 6)
#>                 mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#> Mazda RX4      21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
#> Mazda RX4 Wag  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
#> Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
#> Valiant        18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
#> Merc 280       19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
#> Merc 280C      17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
#> Ferrari Dino   19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6

reprex 包 (v0.3.0) 于 2020 年 7 月 8 日创建

Created on 2020-07-08 by the reprex package (v0.3.0)

这篇关于什么是“拥抱运算符"?`{{}}`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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