4.6 Indexing vectors

Access elements of a vector with [ ], for example myvec[1] to get the first element.

    myvec[1]
## [1] 10
    myvec[2]
## [1] 20

You can also assign to a specific element of a vector.

    myvec[2] <- 5
    myvec
## [1] 10  5 30 40 50

Can we use a vector to index another vector? Yes!

    myind <- c(4,3,2)
    myvec[myind]
## [1] 40 30  5

We could equivalently have written:

    myvec[c(4,3,2)]
## [1] 40 30  5

4.6.1 Challenge: indexing

We can create and index character vectors as well. A teacher is using R to create their class schedule.

classSchedule <- c("science", "math", "reading", "writing", "PE")
classSchedule
## [1] "science" "math"    "reading" "writing" "PE"

Questions

  1. What does classSchedule[-3] produce? Based on what you find, use indexing to create a version of classSchedule without “science.”

  2. Use indexing to create a vector containing science, math, reading, science, and science.

  3. Add a new class, coding, to classSchedule.

4.6.2 Sequences

Another way to create a vector is with a colon :

    1:10
##  [1]  1  2  3  4  5  6  7  8  9 10

This can be useful when combined with indexing:

    classSchedule[1:4]
## [1] "science" "math"    "reading" "writing"

Sequences are useful for other things, such as a starting point for calculations:

    x <- 1:10
    x*x
##  [1]   1   4   9  16  25  36  49  64  81 100
    plot(x, x*x)