R的新原生管道`|>`和magrittr管道`%>%`有什么区别? [英] What are the differences between R's new native pipe `|>` and the magrittr pipe `%>%`?

查看:60
本文介绍了R的新原生管道`|>`和magrittr管道`%>%`有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 R 4.1 中引入了一个更加精简"的本地管道操作符.比以前的实现.我已经注意到本机 |> 和 magrittr 管道 %>% 之间的一个区别,即 2 %>% sqrt 有效但<代码>2 |>sqrt 没有并且必须写为 2 |>sqrt().使用新的管道运算符时是否有更多差异和陷阱需要注意?

In R 4.1 a native pipe operator was introduced that is "more streamlined" than previous implementations. I already noticed one difference between the native |> and the magrittr pipe %>%, namely 2 %>% sqrt works but 2 |> sqrt doesn't and has to be written as 2 |> sqrt(). Are there more differences and pitfalls to be aware of when using the new pipe operator?

推荐答案

R 4.1.0 just"中添加的基本 R 管道 |>做功能组合.IE.我们可以看到它的使用真的和函数调用是一样的:

The base R pipe |> added in R 4.1.0 "just" does functional composition. I.e. we can see that its use really is just the same as the functional call:

> 1:5 |> sum()             # simple use of |>
[1] 15
> deparse(substitute( 1:5 |> sum() ))
[1] "sum(1:5)"
> 

这会产生一些后果:

  • 它使它变得更快
  • 它让它变得更简单、更健壮
  • 它限制了一些:sum() 这里需要括号来正确调用
  • 它限制了隐式"数据参数的使用
  • it makes it a little faster
  • it makes it a little simpler and more robust
  • it makes is a little more restrictive: sum() here needs the parens for a proper call
  • it limits uses of the 'implicit' data argument

这导致可能使用 =>,它当前可用但未激活";(为此您需要设置环境变量 _R_USE_PIPEBIND_,并且在 R 4.2.0 中可能会更改).

This leads to possible use of => which is currently "available but not active" (for which you need to set the enviornment variable _R_USE_PIPEBIND_, and which may change for R 4.2.0).

(这最初是作为对重复此的问题的回答而提供的在这里,我只是按照建议复制了它.)

(This was first offered as answer to a question duplicating this over here and I just copied it over as suggested.)

随着关于什么是 =>"的后续问题出现,这里是一个快速跟进.请注意,此运算符可能会发生变化.

As the follow-up question on 'what is =>' comes up, here is a quick follow-up. Note that this operator is subject to change.

> Sys.setenv("_R_USE_PIPEBIND_"=TRUE)
> mtcars |> subset(cyl == 4) |> d => lm(mpg ~ disp, data = d)

Call:
lm(formula = mpg ~ disp, data = subset(mtcars, cyl == 4))

Coefficients:
(Intercept)         disp  
     40.872       -0.135  

> deparse(substitute(mtcars |> subset(cyl==4) |> d => lm(mpg ~ disp, data = d)))
[1] "lm(mpg ~ disp, data = subset(mtcars, cyl == 4))"
> 

deparse(substitute(...)) 在这里特别好.

这篇关于R的新原生管道`|>`和magrittr管道`%>%`有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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