将算术运算符视为函数
Treat arithmetic operators as functions
我读到 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))
是的,你可以:
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
要调用没有语法有效名称的对象(例如函数 +
,如果您执行 1 + 2
之类的操作则隐式调用该函数),您需要将名称括在反引号中 ( `) 或引号(" 或 ')。
另请参阅 R Language Definition 的第 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). Notice that since ‘+’ is a non-standard function name, it needs to be quoted.
在您的代码中出现错误:
Error: unexpected ',' in "zz <- +(if(exists("xx")) length(xx),"
这是因为您不调用(二元)函数 "+"
,而是调用一元运算符 +
,它不需要函数参数,因此将括号解释为 "arithmetic" 运算符。两者之间不允许使用逗号。
我读到 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))
是的,你可以:
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
要调用没有语法有效名称的对象(例如函数 +
,如果您执行 1 + 2
之类的操作则隐式调用该函数),您需要将名称括在反引号中 ( `) 或引号(" 或 ')。
另请参阅 R Language Definition 的第 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). Notice that since ‘+’ is a non-standard function name, it needs to be quoted.
在您的代码中出现错误:
Error: unexpected ',' in "zz <- +(if(exists("xx")) length(xx),"
这是因为您不调用(二元)函数 "+"
,而是调用一元运算符 +
,它不需要函数参数,因此将括号解释为 "arithmetic" 运算符。两者之间不允许使用逗号。