4.6 Indexing vectors
Access elements of a vector with [ ]
, for example myvec[1]
to get
the first element.
1] myvec[
## [1] 10
2] myvec[
## [1] 20
You can also assign to a specific element of a vector.
2] <- 5
myvec[ myvec
## [1] 10 5 30 40 50
Can we use a vector to index another vector? Yes!
<- c(4,3,2)
myind myvec[myind]
## [1] 40 30 5
We could equivalently have written:
c(4,3,2)] myvec[
## [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.
<- c("science", "math", "reading", "writing", "PE")
classSchedule classSchedule
## [1] "science" "math" "reading" "writing" "PE"
Questions
-
What does
classSchedule[-3]
produce? Based on what you find, use indexing to create a version of classSchedule without “science.” -
Use indexing to create a vector containing science, math, reading, science, and science.
-
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:
1:4] classSchedule[
## [1] "science" "math" "reading" "writing"
Sequences are useful for other things, such as a starting point for calculations:
<- 1:10
x *x x
## [1] 1 4 9 16 25 36 49 64 81 100
plot(x, x*x)