5 Vectors
5.1 Vectors
Vectors are ordered list of values.
- Vectors can be of any data type
- numeric
- character
- logic
- All items in a vector have to be of the same type
- Vectors can be of any length
5.2 Defining vectors
A vector variable can be defined using
- an identifier (e.g.,
a_vector
) - on the left of an assignment operator
<-
- followed by the object to be linked to the identifier
- in this case, the result returned by the function
c
- which creates a vector containing the element provided as input
a_vector <- c("Birmingham", "Derby", "Leicester",
"Lincoln", "Nottingham", "Wolverhampton")
a_vector
## [1] "Birmingham" "Derby" "Leicester" "Lincoln"
## [5] "Nottingham" "Wolverhampton"
5.3 Creating vectors
- the operator
:
- the function
seq
- the function
rep
## [1] 4 5 6 7
## [1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0
## [1] 1.0 2.5 4.0 5.5 7.0 8.5 10.0
## [1] "Ciao" "Ciao" "Ciao" "Ciao"
5.4 Selection
Each element of a vector can be retrieved specifying the related index between square brackets, after the identifier of the vector. The first element of the vector has index 1.
## [1] "Leicester"
A vector of indexes can be used to retrieve more than one element.
## [1] "Nottingham" "Leicester"
5.5 Functions on vectors
Functions can be used on a vector variable directly
## [1] 11 12 13 14 15
## [1] 1.000000 1.414214 1.732051 2.000000 2.236068
## [1] FALSE FALSE TRUE TRUE TRUE
5.6 Any and all
Overall expressions can be tested using the functions:
- any, TRUE if any of the elements satisfies the condition
- all, TRUE if all of the elements satisfy the condition
## [1] TRUE
## [1] FALSE