在这种情况下,map2_dbl 是如何知道它的参数的?

How did the map2_dbl know what its arguments were in this instance?

我正在阅读 Wickham's book 并且遇到了这段代码:

models <- models %>% 
mutate(dist = purrr::map2_dbl(a1, a2, sim1_dist))

models

> # A tibble: 250 × 3
>       a1      a2  dist
>    <dbl>   <dbl> <dbl>
> 1 -15.15  0.0889  30.8
> 2  30.06 -0.8274  13.2
> 3  16.05  2.2695  13.2
> 4 -10.57  1.3769  18.7
> 5 -19.56 -1.0359  41.8#> 6   7.98  4.5948  19.3
>  ... with 244 more rows

我原以为这段代码会产生错误; tibble "models" 是 mutate 函数的参数;我很惊讶函数 map2_dbl 知道要回到那里去找 a1, a2。

我原以为有必要做这样的事情:

mutate(dist = purrr::map2_dbl(models$a1, models$a2, sim1_dist))

我的问题是:这是 R 中函数的正常行为,还是 map2_dbl 或 mutate 函数有什么特别之处?是否有任何其他功能表现出这种行为?

这是 non-standard evaluation 的 属性,mutatedplyr 包中的其他动词被广泛使用。但是,这并不特定于 dplyr 或其他包。从基数 R:

考虑 subset
## Create a simple data frame
X <- data.frame( a = 1:5, b = 11:15 )

## Notice that I can refer to the columns a and b without doing X$a and X$b
subset( X, a > 1 & b < 15 )
#   a  b
# 2 2 12
# 3 3 13
# 4 4 14

正如其他人指出的那样,%>% 管道运算符只是简单地获取其 left-hand 参数并将其传递给其 right-hand 参数,从而使以下内容等同于上述内容:

X %>% subset( a > 1 & b < 15 )