如何从中缀函数的名称中删除 %?

How one can delete % from the name of an infix function?

R是否可以定义(+)函数,s.t。能够在它的两个参数之间工作吗?

换句话说,我想从以下中缀函数中删除%(但我不能,我不知道如何解决这个问题):

`%(+)%` <- function(x,y)  { x+(2*y) }
2 %(+)% 3

用户定义的中缀运算符 必须 在 R 中被百分号包围。所以你的问题的答案是 "you can't"。对不起。

来自R language definition

R allows user-defined infix operators. These have the form of a string of characters delimited by the ‘%’ character. The string can contain any printable character except ‘%’. The escape sequences for strings do not apply here.

我能想到的唯一选择,都相当绝望:

  • 如果 xy 被定义为 S4 class 的成员,那么您可以 overload dispatch for the + symbol
  • 您可以破解 R 解析器(不推荐!),如 this example, where someone forked a read-only Github mirror of R to modify the parser (described here)。

我同意 Ben Bolker 的观点,您不能在没有 % 的情况下定义 (+)。但是,如果您希望按照上述方式创建函数,为什么不使用以下内容:

`&`<- function(x, y) { x+(2*y) }
2&3
#Use rm to remove the defined function
rm(`&`)