R Operators


R is quite rich in operators it provides. Not be as rich as Perl - but, the operators in R are taylored towards handling chunks of data. By default all the operators when applied on vectors perform the operation on individual corresponding elements. Operators in R can be classified into 5 major types:

Arithmetic


R defines these arithmetic operators +, -, *, /, %%, %/%, ^

The meaning of +, -, *, /, ^ is the same as in most other languages. That does not need any clarification. The %% and %/% are more interesting. Both are related to integer division. One gives the quotient and the other gives the remainder

> # / performs the usual division
> c(4, 2, 5.5, 6.5) / c(2, 4, 2.5, 3)
[1] 2.000000 0.500000 2.200000 2.166667

> # %% gives the remainder. Note that both the operands could be non integers. 
> # But the operator ensures integer division.
> c(4, 2, 5.5, 6.5) %% c(2, 4, 2.5, 3)
[1] 0.0 2.0 0.5 0.5

> # %/% gives the quotient. Note that both the operands could be non integers. 
> # But the operator ensures integer division.
> c(4, 2, 5.5, 6.5) %/% c(2, 4, 2.5, 3)
[1] 2 0 2 2

Relational


R defines the usual relational operators: <, >, =<, >=, ==, !=

They mean almost what they would mean in any other language. But, as mentioned above, the operators work on individual elements in the vector and produce another vector of boolean elements that stand for the result of each individual comparison. For example:

> c(4, 2, 5.5, 6.5) < c(2, 4, 2.5, 3)
[1] FALSE  TRUE FALSE FALSE

Logical


R defines all the usual logical operators: &, |, !, && and ||

The operators &, | and ! do just what one would expect - operate on individual elements of the operand vectors and produce another boolean vector as result. But the && and || work differently - They just operate on the first elements of the vectors and return a single boolean value based on that.

Assignment


There are two types of assignments in R. Left assignment and Right assignment.

> a <- c(1,2,3)
> a
[1] 1 2 3
> c(3,4,5,6) -> a
> a
[1] 3 4 5 6

You can also use <<-, ->> and ofcourse = There are subtle differences between these - we will check them out down the line.

Miscellaneous


R also provides other operators :, %in% and %*%

print(2:8) 
[1] 2 3 4 5 6 7 8

print(8 %in% 1:10) 
[1] TRUE
print(12 %in% 1:10)
[1] FALSE

These are not limited to numbers. They work as well on other data types.