Apo*_*los 14 syntax r function
我已经读过R中的所有东西都是功能.所以我想知道"+"是否也是一个函数,如果我们可以写出类似的东西:
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))
Run Code Online (Sandbox Code Playgroud)
Rol*_*and 21
是的你可以:
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
Run Code Online (Sandbox Code Playgroud)
要调用没有语法上有效名称的对象(例如,+
如果你执行类似操作会隐式调用的函数1 + 2
),则需要将名称括在反引号(`)或引号("或")中.
另见R语言定义的第3.1.4节:
除了语法之外,应用运算符和调用函数之间没有区别.实际上,x + y可以等效地写成`+`(x,y).请注意,由于'+'是非标准函数名称,因此需要引用它.
在您的代码中,您会收到错误:
Error: unexpected ',' in "zz <- +(if(exists("xx")) length(xx),"
Run Code Online (Sandbox Code Playgroud)
这是因为你没有调用(二进制)函数"+"
,而是调用一元运算符+
,它不期望函数参数,因此将括号解释为"算术"运算符.这些之间不允许使用逗号.