Monday, 15 June 2015

R : Vector Arithmetic

You can perform arithmetic operations on vectors.
> vector1 <- 1:6
> vector2 <- 7:12
> 
> vector1
[1] 1 2 3 4 5 6
> vector2
[1]  7  8  9 10 11 12
> 
> vector1 + vector2
[1]  8 10 12 14 16 18
> 
> vector1-vector2
[1] -6 -6 -6 -6 -6 -6
> 
> vector2-vector1
[1] 6 6 6 6 6 6
> 
> vector1 * vector2
[1]  7 16 27 40 55 72
> 
> vector2/vector1
[1] 7.0 4.0 3.0 2.5 2.2 2.0
> 
> 5*vector1
[1]  5 10 15 20 25 30
> 
> 6*vector2
[1] 42 48 54 60 66 72

Recycling rule

If two vectors of unequal length, then while performing operations, the shorter vector will be recycled in order to match longer vector.

> vector1 <- 1:3
> vector2 <- 1:17
> 
> vector1
[1] 1 2 3
> vector2
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17
> 
> 
> vector1 + vector2
 [1]  2  4  6  5  7  9  8 10 12 11 13 15 14 16 18 17 19
Warning message:
In vector1 + vector2 :
  longer object length is not a multiple of shorter object length



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment