R 中的从右到左运算符结合性是否可能? [英] Is right-to-left operator associativity in R possible?
问题描述
我是 R 新手,我刚刚发现我患有支架恐惧症(请参阅关联).我喜欢 magrittr
符号 %>%
的工作方式,因为它在某些情况下避免了嵌套括号,并使代码更具可读性.我来自 Mathematica
,那里有一个非常相似的原生 //
符号来做 %>%
所做的事情.下面是一些 R 和 Mathematica 的比较:
I'm new to R, and I just discovered I suffer from Bracket Phobia (see comment in the link). I like the way magrittr
notation %>%
works, because it avoids nested parenthesis in some situations, and makes code more readable. I came from Mathematica
, where there is a very similar native //
notation to do what %>%
does. Here are some R and Mathematica comparisons:
#R Notation
c(1.5,-2.3,3.4) %>% round %>% abs %>% sum
#Mathematica Notation
{1.5,-2.3,3.4}//Round//Abs//Total
到目前为止一切顺利,但是,我的问题是:
So far so good, but, my question is:
有什么方法可以模仿 Mathematica @ 符号,R
中的从右到左结合性?
Is there some way to mimic Mathematica @ notation, with right-to-left associativity in R
?
这是它在 Mathematica 中的工作原理,用于解决上面相同的代码:
Here is how it works in Mathematica, to solve the same code above:
Total@Abs@Round@{1.5,-2.3,3.4}
在 Mathematica 中也可以写成:
In Mathematica it can also be write as:
Total[Abs[Round[{1.5,-2.3,3.4}]]]
就像在 R
中一样:
sum(abs(round(c(1.5,-2.3,3.4))))
但是在 R
中有这样的东西会更干净(也很酷):
But it would be much more clean (and cool) to have in R
something like this:
sum@abs@round@c(1.5,-2.3,3.4)
PS:我知道 @
在 S4 类中使用,这不是一个好主意.这只是一个说明性的比较.
PS: I know @
is used in S4 classes, and is not a good idea. This is just an illustrative comparison.
推荐答案
backpipe 包就是为此目的而设计和创建的.它为 magrittr、pipeR 和任何前向管道操作符提供了一个 backpipe(从右到左)操作符.backpipe 可以在 github 和 CRAN.
The backpipe package was designed and created for this purpose. It provides a backpipe (right-to-left) operator for magrittr, pipeR and generally for any forward pipe operator. backpipe can be found on github and on CRAN.
library(magrittr) # or library(pipeR)
library(backpipe)
x <- c(1.5,-2.3,3.4)
sum %<% abs %<% round %<% x
all.equal( # TRUE
x %>% round %>% abs %>% sum,
sum %<% abs %<% round %<% x
)
backpipe 也不受其他参数的限制,就像@BenBolker 的解决方案一样.例如,这适用于 backpipe :
backpipe also is not limited by additional parameters as is the case of the @BenBolker's solution. This, for example, works with backpipe :
mean(na.rm=TRUE) %<% c(1:3,NA)
另请参阅有关讨论此问题的 magrittr github 问题 的讨论.
See also the discussion on the magrittr github issue that discuss this.
这篇关于R 中的从右到左运算符结合性是否可能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!