October 1st, 2018
There are two ideas here:
Vectors are so useful that we have several ways to create them
For example, the function c(3,1,4)
will give us a vector
We can also make vectors with incrementing numbers or repeating numbers
A vector with numbers between 4 and 9
4:9
[1] 4 5 6 7 8 9
seq(4, 9)
[1] 4 5 6 7 8 9
The two commands are equivalent. The first is easier to write
We can go from 4 to 10 incrementing by 2
seq(4, 10, 2)
[1] 4 6 8 10
We can say how many numbers we want, instead of the last value
seq(from=4, by=2, length=4)
[1] 4 6 8 10
rep(1, 3)
[1] 1 1 1
rep(c(7, 9, 13), 3)
[1] 7 9 13 7 9 13 7 9 13
rep(c(7, 9, 13), 1:3)
[1] 7 9 9 13 13 13
rep(1:2, c(10, 5))
[1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2
rep(c(TRUE, FALSE), 3)
[1] TRUE FALSE TRUE FALSE TRUE FALSE
rep(c(TRUE, FALSE), c(3, 3))
[1] TRUE TRUE TRUE FALSE FALSE FALSE
c(NA, TRUE, FALSE)
[1] NA TRUE FALSE
c(NA, 1, 2)
[1] NA 1 2
To get the i-th element of a vector v
we use v[i]
weight <- c(60, 72, 57, 90, 95, 72) weight
[1] 60 72 57 90 95 72
weight[3]
[1] 57
The value inside []
is called index (plural: indices)
weight[c(1,3,5)]
[1] 60 57 95
weight[2:4]
[1] 72 57 90
Used to indicate omitted elements
weight
[1] 60 72 57 90 95 72
weight[c(-1,-3,-5)]
[1] 72 90 72
Useful when you need almost all elements
Vectors can be indexed by a logical vector
Must be of the same length of the vector
weight>72
[1] FALSE FALSE FALSE TRUE TRUE FALSE
weight[weight>72]
[1] 90 95
This is very useful
Every element of a vector can have a name
names(weight) <- c("Ali", "Deniz", "Fatma", "Emre", "Volkan", "Onur") weight
Ali Deniz Fatma Emre Volkan Onur 60 72 57 90 95 72
We can assign names to the elements when we create the vector
height <- c(Ali=1.75, Deniz=1.80, Fatma=1.65, Emre=1.90, Volkan=1.74, Onur=1.91) height
Ali Deniz Fatma Emre Volkan Onur 1.75 1.80 1.65 1.90 1.74 1.91
If a vector has names, we can use them as indices:
weight[c("Deniz", "Volkan", "Fatma")]
Deniz Volkan Fatma 72 95 57
names(vector)
NULL