Data Structure: Vector
↪ Creating Vector
A vector in R can contain any number of elements, but all of the elements must be of the same type – that is a vector cannot contain a mix of numbers, logical, and character types.
The c() function is used for creating the Vector. “=” or “->” can be used as an assignment operator.
x = c(5,8,10,12) x
---Output--- [1] 5 8 10 12
The vector can also be given a name using the <- operator, much like the = assignment operator.
x <- c("A","B","X","Z") x
—Output— [1] “A” “B” “X” “Z”
The typeof() function is used for finding the data type present in the vector.
typeof(x)
---Output--- [1] "double"
By default, a number is considered double in R. To create an integer Vector, append the number by L.
x = c(5L,8L,10L,12L) typeof(x)
---Output--- [1] "integer"
Data Structure: Vector
↪ Vector of Sequence
The ':' operator is used for creating a sequence with the vector function c().
x = c(1:15) x
---Output--- [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
A sequence can be created simply by
x = 1:15 x
The seq() function is used for creating a sequence.
x = seq(1,15) x
Sequence with increment value.
x = seq(1,15,3) x
---Output--- [1] 1 4 7 10 13
Another example of sequence with fraction incremental value.
x = seq(0,1,0.1) x
---Output--- [1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
Data Structure: Vector
↪ Accessing an element in the vector
Accessing an element using an index.
x[3]
Accessing range of elements in the vector.
x[5:8]
Exclude an item
x = c(10,20,30,40) x[-3]
---Output--- [1] 10 20 40
A logical vector can be used to indicate whether an item should be included.
x[c(TRUE,FALSE,FALSE,TRUE)]
---Output--- [1] 10 40
Data Structure: Vector
↪ Arithmetic Operations
Arithmetic operations can be performed when the two vectors are of same length.
x = c(10,20,30,40) y = c(20,30,40,50) x + y # Prints [1] 30 50 70 90 y-x # Prints [1] 10 10 10 10 x*y # Prints [1] 200 600 1200 2000 y/x # Prints [1] 2.000000 1.500000 1.333333 1.250000
Other singular arithmetic operations on Vector are possible.
x^2 # Prints [1] 100 400 900 1600 sqrt(x) # Prints [1] 3.162278 4.472136 5.477226 6.324555