Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Treat arithmetic operators as functions

Tags:

syntax

function

r

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))
like image 397
Apostolos Avatar asked Oct 26 '15 15:10

Apostolos


People also ask

What is the function of arithmetic operators?

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.

What are the 4 types of arithmetic operators?

These operators are + (addition), - (subtraction), * (multiplication), / (division), and % (modulo).


1 Answers

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.

like image 177
Roland Avatar answered Oct 03 '22 07:10

Roland