Contents
 
Introduction
To R

Vectors

So far, all the objects we have created have been single values, or scalars. R can also work with vectors - objects that have more than one value.

The c() function creates a vector from all of its scalar arguments. For example:

> x <- c(2,3,5,7,11)   The first five primes
> x
[1]  2  3  5  7 11     Type its name to print
The arguments to c() can be scalars or vectors:
> y <- c(x,13,17,19)       Two more primes
> y
[1]  2  3  5  7 11 13 17 19

Sequences

There are other ways of generating vectors. To generate a sequence of integers between two values, you use a colon:
> xx <- 1:10
> xx
 [1]  1  2  3  4  5  6  7  8  9 10
If your vector is too long to fit on one line, R will print it on the next line:
> xx <- 100:1     Descending sequence 100 to 1 
> xx
  [1] 100  99  98  97  96  95  94  93  92  91  90  89  88  87  86  85  84  83
 [19]  82  81  80  79  78  77  76  75  74  73  72  71  70  69  68  67  66  65
 [37]  64  63  62  61  60  59  58  57  56  55  54  53  52  51  50  49  48  47
 [55]  46  45  44  43  42  41  40  39  38  37  36  35  34  33  32  31  30  29
 [73]  28  27  26  25  24  23  22  21  20  19  18  17  16  15  14  13  12  11
 [91]  10   9   8   7   6   5   4   3   2   1
The numbers in square brackets tell us how far along the vector we are - now we can see what the [1] has been telling us - its the first element on that line!

Using seq()

You can construct more general sequences with the function seq() - giving the start, end, and step size:
> seq(1,10,1)             same as 1:10
 [1]  1  2  3  4  5  6  7  8  9 10
> seq(1,10,2)             step of 2
[1] 1 3 5 7 9             doesn't quite get to 10
> seq(10,1,3)             try going backwards...
Error in seq.default(10, 1, 3): Wrong sign in 'by' argument

> seq(10,1,-3)            need negative step size...
[1] 10  7  4  1           yup, thats fixed it

Using rep()

Another useful vector constructor is the rep() function. It returns a vector that is its first argument repeated the number of times given by its second argument:
> rep(1,10)
 [1] 1 1 1 1 1 1 1 1 1 1
> rep(c(1,2),10)
 [1] 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2
> c(rep(0,10),rep(1,5))
 [1] 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1
There's nothing to stop you using variables as arguments to these functions:
> x <- 10
> rep(c(1,2),x)
 [1] 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2
If given two vector arguments then the elements of the second argument specify the number of repeats of the corresponding element in the first argument. Figure this one out:
> rep(4:1,1:4)
 [1] 4 3 3 2 2 2 1 1 1 1

Contents