Chapter 4 Operator and Loops
4.1 Operator
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. R language is rich in built-in operators and provides following types of operators.
- Arithmetic Operators
- Relational Operators
- Logical Operators
- Assignment Operators
- Miscellaneous Operators
4.1.1 Arithmetic Operators
The following operators act on each element of the vector.
- Adds two vectors (+)
## [1] 10.0 8.5 10.0
- Subtracts second vector from the first (-)
## [1] -6.0 2.5 2.0
- Multiplies both vectors (*)
## [1] 16.0 16.5 24.0
- Divide the first vector with the second (/)
## [1] 0.250000 1.833333 1.500000
- Give the remainder of the first vector with the second (%%)
## [1] 2.0 2.5 2.0
- The result of division of first vector with second (quotient - %/%)
## [1] 0 1 1
- The first vector raised to the exponent of second vector (^)
## [1] 256.000 166.375 1296.000
4.1.2 Relational Operators
R language support: <, <=, >, >=, ==, !=. Each element of the first vector is compared with the corresponding element of the second vector. The result of comparison is a Boolean value.
## [1] FALSE TRUE FALSE FALSE
## [1] TRUE FALSE TRUE FALSE
## [1] FALSE FALSE FALSE TRUE
## [1] TRUE FALSE TRUE TRUE
## [1] FALSE TRUE FALSE TRUE
## [1] TRUE TRUE TRUE FALSE
4.1.3 Logical Operators
It is applicable only to vectors of type logical, numeric or complex. All numbers greater than 1 are considered as logical value TRUE.
Each element of the first vector is compared with the corresponding element of the second vector. The result of comparison is a Boolean value.
- Logical And (&)
## [1] TRUE TRUE FALSE TRUE
- Logical Or (|)
## [1] TRUE FALSE TRUE TRUE
- Logical NOT (!)
## [1] FALSE TRUE FALSE FALSE
The logical operator && and || considers only the first element of the vectors and give a vector of single element as output.
- Logical AND (&&)
## [1] TRUE
- Logical OR (||)
## [1] FALSE
4.1.4 Assignment Operators
These operators are used to assign values to vectors.
- Left Assignment (<-, <<-, =)
## [1] 3+0i 1+0i 1+0i 2+3i
## [1] 3+0i 1+0i 1+0i 2+3i
## [1] 3+0i 1+0i 1+0i 2+3i
- Right Assignment (->, ->>)
## [1] 3+0i 1+0i 1+0i 2+3i
## [1] 3+0i 1+0i 1+0i 2+3i
4.1.5 Miscellaneous Operators
These operators are used to for specific purpose and not general mathematical or logical computation.
- Colon operator, it creates the series of numbers in sequence for a vector (:)
## [1] 2 3 4 5 6 7 8
- This operator is used to identify if an element belongs to a vector. (%in%)
## [1] TRUE
## [1] FALSE
- This operator is used to multiply a matrix with its transpose (%*%)
## [,1] [,2]
## [1,] 65 82
## [2,] 82 117