<- 9:18
a a
[1] 9 10 11 12 13 14 15 16 17 18
<- 18:9
a_rev a_rev
[1] 18 17 16 15 14 13 12 11 10 9
<- 5:-3
a_rev_minus a_rev_minus
[1] 5 4 3 2 1 0 -1 -2 -3
Part 5: Vectors
William Okech
November 12, 2022
A vector is a collection of elements of the same data type, and they are a basic data structure in R programming.
Vectors cannot be of mixed data type. The most common way to create a vector is with c()
, where “c” stands for combine. In R, vectors do not have dimensions; therefore, they cannot be defined by columns or rows. Vectors can be divided into atomic vectors and lists (discussed in Part 7). The atomic vectors include logical, character, and numeric (integer or double).
Additionally, R is a vectorized language because mathematical operations are applied to each element of the vector without the need to loop through the vector.Examples of vectors are shown below:
• Numbers: c(2, 10, 16, -5)
• Characters: c("R", "RStudio", "Shiny", "Quarto")
• Logicals: c("TRUE", "FALSE", "TRUE")
To generate a vector with a sequence of consecutive numbers, we can use :
, sequence()
, or seq()
.
:
sequence()
seq()
The seq()
function has four main arguments: seq(from, to, by, length.out), where “from” and “to” are the starting and ending elements of the sequence. Additionally, “by” is the difference between the elements, and “length.out” is the maximum length of the vector.
To create a repeating vector, we can use rep()
.
Vectors of equal length can be operated on together. If one vector is shorter, it will get recycled, as its elements are repeated until it matches the elements of the longer vector. When using vectors of unequal lengths, it would be ideal if the longer vector is a multiple of the shorter vector.
[1] 12 24 36 48 60 72 84 96 108 120
[1] 13 14 15 16 17 18 19 20 21 22
[1] -11 -10 -9 -8 -7 -6 -5 -4 -3 -2
[1] 0.3333333 0.6666667 1.0000000 1.3333333 1.6666667 2.0000000 2.3333333
[8] 2.6666667 3.0000000 3.3333333
[1] 1 16 81 256 625 1296 2401 4096 6561 10000
[1] 1.000000 1.414214 1.732051 2.000000 2.236068 2.449490 2.645751 2.828427
[9] 3.000000 3.162278
Additionally, we can perform operations on two vectors of equal length.
[1] 17 17 17 17 17 17 17 17 17 17
[1] -7 -5 -3 -1 1 3 5 7 9 11
[1] 0.4166667 0.5454545 0.7000000 0.8888889 1.1250000 1.4285714 1.8333333
[8] 2.4000000 3.2500000 4.6666667
[1] 60 66 70 72 72 70 66 60 52 42
[1] 244140625 362797056 282475249 134217728 43046721 10000000 1771561
[8] 248832 28561 2744
The functions listed below can be applied to vectors:
any()
all()
nchar()
length()
typeof()
Determine the number of letters in a character
To access the elements of a vector, we can use numeric-, character-, or logical-based indexing.
names()
.Create the vector.
Name the individual elements.