Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将算术运算符视为函数_R_Function_Syntax - Fatal编程技术网

R 将算术运算符视为函数

R 将算术运算符视为函数,r,function,syntax,R,Function,Syntax,我读过,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是的,您可以: xx <- c(1,2,3) yy <- c(1,2,3,4,5,6) # z

我读过,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是的,您可以:

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

这是因为您不调用(二进制)函数
“+”
,而是调用一元运算符
+
,它不需要函数参数,因此将括号解释为“算术”运算符。它们之间不允许使用逗号。

只需使用
sum
而不是
+
+
确实是一个只需添加回刻度的函数。但是,使用
if(exists())
的构造在
+
函数调用中的工作方式与预期不同。试试如果其中一个变量不存在会发生什么。你基本上是这样做的:
1+NULL
。@Ronald:你说得对。我通过将“if”改为“ifelse”来修复它。另请参见,您也可以使用单引号或双引号、
“+”(1,1)
“+”(1,1)
这两种方法都能起到反勾号解决方案的作用。规则是,除了分隔函数参数外,任何地方都不允许使用逗号。
Error: unexpected ',' in "zz <- +(if(exists("xx")) length(xx),"