I've read that everything in R is function. 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))
Arithmetic Operators are used to perform mathematical calculations. Assignment Operators are used to assign a value to a property or variable. Assignment Operators can be numeric, date, system, time, or text. Comparison Operators are used to perform comparisons.
These operators are + (addition), - (subtraction), * (multiplication), / (division), and % (modulo).
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 ').
See also Section 3.1.4 of the R Language Definition:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With