Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is unary plus / minus in R?

Tags:

r

From the Details section of R's Syntax help page:

The following unary and binary operators are defined. They are listed in precedence groups, from highest to lowest.
[some operators]
- + unary minus and plus
[some more operators]
+ - (binary) add, subtract

What is unary plus/minus ?

Where is the difference between unary plus(+)/minus (-) and binary addition (+) or subtraction(-) in R?

like image 263
time Avatar asked Jan 02 '15 07:01

time


1 Answers

The arity of an operator tells on how many arguments it operates. Unary works on a single argument, binary works on two arguments, ternary works on three arguments, etc.

-a
^

That is an unary minus. It negates the value of the single argument/expression that follows it. You might think of it as a function call like minus(a) that changes the sign of its argument and returns that as result. Unary plus also exists but it is basically a no-op.

a - b
  ^

That is a binary minus. It takes the value of its two arguments/expressions and subtracts the second one from the first one. You might think of it as a function call like minus(a,b) that takes two arguments and returns their difference. Binary plus returns the sum.


As noted by @BondedDust, in R (and in other languages that support vector processing) some operators actually take vector arguments and then perform their action on each element separately. For example, the unary minus sign-inverts all elements of a vector:

> -(-2:2)
[1]  2  1  0 -1 -2

or as a function call:

> `-`(-2:2)
[1]  2  1  0 -1 -2

The binary minus subtracts two vectors element-wise:

> 1:5 - 5:1
[1] -4 -2  0  2  4

or as a function call:

> `-`(1:5, 5:1)
[1] -4 -2  0  2  4

The minus operator in R is a function with two arguments:

> `-`
function (e1, e2)  .Primitive("-")

When both arguments are present, it performs the operation of the binary minus, i.e. subtracts e2 from e1 element-wise. When only e1 is present, it operates as a unary minus and sign-inverts the elements of e1.

The same applies to the plus operator. One has to be careful and to not confuse the plus operator + with the sum function. + operates element-wise on one (as an unary operator) or on two (as a binary operator) vector arguments while sum sums all values present in its arguments. And while sum could take any number of arguments:

> sum
function (..., na.rm = FALSE)  .Primitive("sum")

the + operator takes only one or two:

> `+`(1, 2, 3)
Error in `+`(1, 2, 3) : operator needs one or two arguments
like image 133
Hristo Iliev Avatar answered Sep 27 '22 19:09

Hristo Iliev