1
2
3
4
5
#

R: Vector Arithmetic

Let's begin by creating two vectors, x and y.
> #create a vector x with 5 components
> x=c(1,3,2,10,5)
> x
[1]  1  3  2 10  5
>
> #create a vector y consisting of 1 through 5
> y=1:5
> y
[1] 1 2 3 4 5

R code that will create a new vector by manipulating vector y.

> y + 4                 # scalar addition
[1] 5 6 7 8 9
> 3*y                 # scalar multiplication
[1]  3  6  9 12 15
> y^3                 # raise each component to the third power
[1]   1   8  27  64 125
> 2^y                 # raise 3 to the first through fifth power
[1]  2  4  8 16 32
> y                   # y itself has not been unchanged
[1] 1 2 3 4 5
> y = y*2             # redefine y - y is now changed
> y
[1]  2  4  6  8 10

Now, lets combine two vectors in various ways to create new vectors.

> x+y                # add x and y
[1]  3  7  8 18 15
> x*y                # multiply x and y
[1]  2 12 12 80 50
> x/y               # divide x and y
[1] 0.5000000 0.7500000 0.3333333 1.2500000 0.5000000
> x^y                # raise each x term to the corresponding y term
[1]         1        81        64 100000000   9765625
> z=x+y            # add x and y, then assign to term z
> z                   # request
[1]  3  7  8 18 15