4.5 Vectors

A vector of numbers is a collection of numbers. “Vector” means different things in different fields (mathematics, geometry, biology), but in R it is a fancy name for a collection of values. We call the individual values elements of the vector.

We can make vectors with the function c( ), for example c(1,2,3). c means “combine.” R is obsesssed with vectors, in R even single numbers are vectors of length one. Many things that can be done with a single number can also be done with a vector. For example arithmetic can be done on vectors as it can be on single numbers.

    myvec <- c(10,20,30,40,50)
    myvec
## [1] 10 20 30 40 50

Add 1 to each element of the vector.

    myvec + 1
## [1] 11 21 31 41 51

Add vectors together

    myvec + myvec
## [1]  20  40  60  80 100

Determine the length of the vector.

    length(myvec)
## [1] 5

Add an element to a vector at the beginning or end.

    c(60, myvec)
## [1] 60 10 20 30 40 50
    c(myvec, 60)
## [1] 10 20 30 40 50 60

Combine vectors.

    c(myvec, myvec)
##  [1] 10 20 30 40 50 10 20 30 40 50

Be careful!
Beware when working on vectors of different lengths that R will recycle to the beginning of the shorter length vector.

    myvec2 <- c(10,20,30,40,50,60)
    myvec2
## [1] 10 20 30 40 50 60
    length(myvec2)
## [1] 6
    myvec+myvec2
## Warning in myvec + myvec2: longer object length is not a multiple of shorter
## object length
## [1]  20  40  60  80 100  70

Its helpful to think of the length of a vector as the number of elements in the vector.

We will also encounter vectors of character strings, for example “hello” or c("hello","world"). Also we will encounter “logical” vectors, which contain TRUE and FALSE values. (Are factors really vectors? - Amy) R also has “factors,” which are categorical vectors, and behave much like character vectors (think the factors in an experiment).

4.5.1 Mixing types

Sometimes the best way to understand R is to try some examples and see what it does.

Questions 1. What happens when you try to make a vector containing different types, using c( )?

  1. Make a vector with some numbers, and some words (eg. character strings like “test”, or “hello”).

  2. Why does the output show the numbers surrounded by quotes " " like character strings are?

Because vectors can only contain one type of thing, R chooses a lowest common denominator type of vector, a type that can contain everything we are trying to put in it. A different language might stop with an error, but R tries to soldier on as best it can. A number can be represented as a character string, but a character string can not be represented as a number, so when we try to put both in the same vector R converts everything to a character string.