[英]Treat arithmetic operators as functions
I've read that everything in R is function. 我已经读过R中的所有东西都是功能。 So I wonder if "+" is a function too and if we can write something like that:
所以我想知道“+”是否也是一个函数,如果我们可以写出类似的东西:
xx <- c(1,2,3)
yy <- c(1,2,3,4,5,6)
# zz is the sum of the two lengths
zz <- +(if(exists("xx")) length(xx), if(exists("yy")) length(yy))
Yes, you can: 是的你可以:
xx <- c(1,2,3)
yy <- c(1,2,3,4,5,6)
# zz is the sum of the two lengths
zz <- `+`(if(exists("xx")) length(xx), if(exists("yy")) length(yy))
#[1] 9
To call objects that don't have syntactically valid names (such as the function +
that gets called implicitly if you do something like 1 + 2
) you need to enclose the name in backticks (`) or quotes (" or '). 要调用没有语法有效名称的对象(例如,如果执行类似
1 + 2
操作,则隐式调用的函数+
)需要将名称括在反引号(`)或引号(“或”)中。
See also Section 3.1.4 of the R Language Definition : 另见R语言定义的第3.1.4节:
Except for the syntax, there is no difference between applying an operator and calling a function.
除了语法之外,应用运算符和调用函数之间没有区别。 In fact, x + y can equivalently be written `+`(x, y).
实际上,x + y可以等效地写成`+`(x,y)。 Notice that since '+' is a non-standard function name, it needs to be quoted.
请注意,由于'+'是非标准函数名称,因此需要引用它。
In your code you get the error: 在您的代码中,您会收到错误:
Error: unexpected ',' in "zz <- +(if(exists("xx")) length(xx),"
This is because you don't call the (binary) function "+"
, but the unary operator +
, which doesn't expect function arguments and thus interprets the parentheses as the "arithmetic" operator. 这是因为你没有调用(二进制)函数
"+"
,而是一元运算符+
,它不期望函数参数,因此将括号解释为“算术”运算符。 A comma is not allowed between those. 这些之间不允许使用逗号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.