# Working with Vectors¶

We can perform basics arithmetic with vectors and operations will occur on an element by element basis, for example:

In [1]:

    v1 <- c(1,2,3)
    v2 <- c(5,6,7)

### Adding Vectors¶

In [2]:

    v1+v2

Out[2]:

1. 6
2. 8
3. 10

### Subtracting Vectors¶

In [3]:

    v1-v1

Out[3]:

1. 0
2. 0
3. 0

In [4]:

    v1-v2

Out[4]:

1. -4
2. -4
3. -4

### Multiplying Vectors¶

In [5]:

    v1*v2

Out[5]:

1. 5
2. 12
3. 21

### Dividing Vectors¶

In [6]:

    v1/v2

Out[6]:

1. 0.2
2. 0.333333333333333
3. 0.428571428571429

# Functions with Vectors¶

Let's learn about some useful functions that we can use with vectors! A function will be in the form:

name_of_function(input)

later on we will learn about creating our own functions, but R comes with abunch of built-in functions that you will commonly use.

For example, if you want to sum all the elements in a numeric vector, you can use the sum() function. For example:

In [8]:

    v1

Out[8]:

1. 1
2. 2
3. 3

In [7]:

    sum(v1)

Out[7]:
6

We can also check for things like the standard deviation, variance, maximum element, minimum element, product of elements:

In [13]:

    v <- c(12,45,100,2)

In [14]:

    # Standard Deviation
    sd(v)

Out[14]:
44.1691823182937
In [18]:

    #Variance
    var(v)

Out[18]:
1950.91666666667
In [19]:

    # Maximum Element
    max(v)

Out[19]:
100
In [20]:

    #Minimum Element
    min(v)

Out[20]:
2
In [22]:

    # Product of elements
    prod(v1)
    prod(v2)

Out[22]:
6
Out[22]:
210

This is definitely not all of the functions available that are built in to R! We will be using them over and over again throughout the course, so don't worry too much about memeorizing them, you will naturally begin to remember them more and more as you use them.

Want a reference for all the functions available? Check out this R Reference Card

Ok, that's it for now for basic vector operations!