What is unary plus / minus in R?

In the Details section of the R Syntax help page:

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

What is unary plus / minus?

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

+6
source share
1 answer

The arity of the operator indicates how many arguments it works. Unary works on one argument, binary works on two arguments, triple works on three arguments, etc.

-a ^ 

This is a unary minus. This negates the meaning of the single argument / expression that follows it. You can think of it as a function call, for example minus(a) , which changes the sign of its argument and returns it as a result. A unary plus also exists, but basically it's non-op.

 a - b ^ 

This is a binary minus. It takes the value of two arguments / expressions and subtracts the second from the first. You can think of it as calling a function like minus(a,b) , which takes two arguments and returns their difference. Binary plus returns the amount.


As @BondedDust noted, in R (and other languages ​​that support vector processing), some operators actually take vector arguments, and then perform their action on each element separately. For example, a unary minus signifies 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 by the elements:

 > 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 binary minus operation, i.e. subtracts e2 from e1 by elements. When only e1 present, it works as a unary minus and inverts the elements of e1 .

The same goes for the plus operator. You need to be careful not to confuse the plus + operator with the sum function. + uses a wise element on one (as a unary operator) or on two (as a binary operator) vector arguments, and sum sums all the values ​​present in its arguments. And although sum can take any number of arguments:

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

the + operator accepts only one or two:

 > `+`(1, 2, 3) Error in `+`(1, 2, 3) : operator needs one or two arguments 
+10
source

Source: https://habr.com/ru/post/980422/


All Articles