【问题标题】:How did the map2_dbl know what its arguments were in this instance?在这种情况下,map2_dbl 是如何知道它的参数是什么?
【发布时间】:2018-09-15 22:39:21
【问题描述】:

我正在阅读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 函数有什么特别之处?是否有任何其他函数表现出这种行为?

【问题讨论】:

  • %&gt;% operator 将左侧对象传递到右侧。所以%&gt;%后面的函数已经知道这个对象了
  • @SymbolixAU 我同意变异函数应该知道“模型”,但我很惊讶变异函数的参数 map2_dbl 也知道它。
  • @SymbolixAU 我想使用 %>% 运算符在某种意义上比仅仅使用 mutate(models, dist = purrr::map2_dbl(a1, a2, sim1_dist)) 更强?我试过了,但没有用。
  • 如果您查看in the source code,它可能会让您了解它如何跟踪环境和函数参数。
  • 您不需要将a1a2 引用为models$a1models$a2,因为models 之后的管道%&gt;% 可以引用a 的列没有明确提及数据框名称的数据框。 a1a2 现在也是向量,可以直接输入到 map2_dbl

标签: r purrr


【解决方案1】:

这是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

正如其他人所指出的,%&gt;% 管道运算符只需将其左侧参数传递给其右侧参数,从而使以下等效于上述内容:

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

【讨论】:

    猜你喜欢
    • 2018-10-29
    • 2013-04-23
    • 2020-11-29
    • 2018-06-25
    • 2016-06-03
    • 1970-01-01
    • 2020-04-04
    • 2017-03-28
    • 2016-08-26
    相关资源
    最近更新 更多