Vector Arithmetic and Logical Operations
In R, vectors are fundamental data structures that allow us to perform both arithmetic and logical operations. These operations are carried out element-wise, without requiring loops.
Arithmetic Operations on Vectors:
We can perform arithmetic operations on vectors of the same length. Here are some examples.
Example:
> v1 <- c(2, 4, 6)
> v2 <- c(1, 2, 3)
> # Addition
> print(v1 + v2)
[1] 3 6 9
> # Subtraction
> print(v1 - v2)
[1] 1 2 3
> # Multiplication
> print(v1 * v2)
[1] 2 8 18
> # Division
> print(v1 / v2)
[1] 2 2 2
> # Exponentiation
> print(v1 ^ v2)
[1] 2 16 216
- If vectors have different lengths, the shorter one is recycled (Recycling Rule in Arithmetic) to perform arithmetic operations.
Example:
> v1 <- c(10, 20, 30, 40)
> v2 <- c(2, 4)
> # Addition
> print(v1 + v2) # v2 is repeated: (2, 4, 2, 4)
[1] 12 24 32 44
> # Subtraction
> print(v1 - v2) # v2 is repeated: (2, 4, 2, 4)
[1] 8 16 28 36
Logical Operations on Vectors:
We can perform logical operations element-wise on vectors. Here are some examples.
Example:
> v1 <- c(10, 20, 30)
> v2 <- c(15, 20, 25)
> # Element-wise comparisons
> print(v1 > v2)
[1] FALSE FALSE TRUE
> print(v1 < v2)
[1] TRUE FALSE FALSE
> print(v1 == v2)
[1] FALSE TRUE FALSE