What is a Vector?
A vector is a collection of elements, all the same type (similar to an array in other programming languages but more versatile).
When using R, you will frequently encounter the four basic vector types viz. logical, character, integer and double (often called numeric).
Create a vector
In R, there are several ways to create a new vector; the simplest is to use the c()
function.
# integer vector
c(1, 2, 3, 4, 5, 6)
[1] 1 2 3 4 5 6
# double vector
c(1*pi, 2*pi, 3*pi, 4*pi)
[1] 3.141593 6.283185 9.424778 12.566371
# character vector
c("red", "green", "blue")
[1] "red" "green" "blue"
# logical vector
c(TRUE, FALSE, TRUE, FALSE)
[1] TRUE FALSE TRUE FALSE
As a vector contains elements of the same type, if you try to combine different type of elements, the c()
function converts (coerces) them into a single type.
# numerics are converted to characters
v <- c(1, 2, 3, "a", "b", "c")
v
[1] "1" "2" "3" "a" "b" "c"
# logical are turned to numerics
v <- c(1, 2, 3, TRUE, FALSE)
v
[1] 1 2 3 1 0
You can check the type of a vector using typeof()
function.
Create a Sequence
You can also create a vector using:
The : Operator
You can generate an equally spaced sequence of numbers, by using the :
sequence operator.
# sequence of numbers from 1 to 10
1:10
[1] 1 2 3 4 5 6 7 8 9 10
The seq() Function
The seq()
function works the same as the :
operator, except you can specify a different increment (step size).
# sequence of numbers from 1 to 10 with increment of 2
seq(from=1,to=10,by=2)
[1] 1 3 5 7 9
The rep() Function
With rep()
function you can generate a sequence by simply repeating certain values.
# repeat a value 6 times
rep(x=1,times=6)
[1] 1 1 1 1 1 1
# repeat a vector 3 times
rep(x=c(1,2,3),times=3)
[1] 1 2 3 1 2 3 1 2 3
Change the Vector Type
By using the as.vector()
function, you can change the vector type.
# Turn numerical vector to character
v <- c(0, 1, 2, 3, 4, 5)
as.vector(v, mode="character")
[1] "0" "1" "2" "3" "4" "5"
# Turn numerical vector to logical
v <- c(0, 1, 2, TRUE, FALSE)
as.vector(v, mode="logical")
[1] FALSE TRUE TRUE TRUE FALSE
Naming a Vector
Each element of a vector can have a name. It allows you to access individual elements by names. You can give a name to the vector element with the names()
function.
v <- c("Apple", "Banana", "Cherry")
names(v) <- c("A", "B", "C")
v
A B C
"Apple" "Banana" "Cherry"
You can also give a name to the vector element while creating a vector.
v <- c("A"="Apple", "B"="Banana", "C"="Cherry")
v
A B C
"Apple" "Banana" "Cherry"
Subsetting Vectors
There are several ways to subset a vector (extract a value from the vector). You can do this by combining square brackets []
with:
- Positive integers
- Negative integers
- Logical values
- Names
Subsetting with Positive Integers
Subsetting with positive integers returns the elements at the specified positions. Note that vector positioning starts from 1.
v <- c("a","b","c","d","e","f")
# select 3rd element
v[3]
[1] "c"
# select 5th element
v[5]
[1] "e"
You can select multiple elements at once by using a vector of indexes.
v <- c("a","b","c","d","e","f")
# select elements from index 2 to 5
v[2:5]
[1] "b" "c" "d" "e"
# select elements from index 1 to 6 by increment 2
v[seq(from=1,to=6,by=2)]
[1] "a" "c" "e"
The indexing vector need not be a simple sequence. You can select elements anywhere within the vector.
v <- c("a","b","c","d","e","f")
# select 1st, 3rd, 5th and 6th element
v[c(1,3,5,6)]
[1] "a" "c" "e" "f"
Subsetting by Negative Integer
Subsetting with negative integers will omit the elements at the specified positions.
v <- c("a","b","c","d","e","f")
# omit first element
v[-1]
[1] "b" "c" "d" "e" "f"
# omit elements from index 2 to 5
v[-2:-5]
[1] "a" "f"
# omit 1st, 3rd and 5th element
v[c(-1,-3,-5)]
[1] "b" "d" "f"
Subsetting by Logical Values
Subsetting with logical values will return the elements where the corresponding logical value is TRUE.
v <- c(1,2,3,4,5,6)
v[c(TRUE,FALSE,TRUE,FALSE,TRUE,FALSE)]
[1] 1 3 5
You can also use a logical vector to select elements based on a condition.
# select even elements
v <- c(1,2,3,4,5,6,7,8,9)
v[v %% 2 == 0]
[1] 2 4 6 8
# skip values from 4 to 7
v <- c(1,2,3,4,5,6,7,8,9)
v[v < 4 | v > 7]
[1] 1 2 3 8 9
Subsetting by Names
Subsetting with names will return the elements having the matching names.
v <- c("A"="Apple", "B"="Banana", "C"="Cherry")
v
A B C
"Apple" "Banana" "Cherry"
# select element 'A'
v["A"]
A
"Apple"
# select element 'B'
v["B"]
B
"Banana"
Modify Vector Elements
Modifying a vector element is pretty straightforward. You use the []
to access the element, and simply assign a new value.
v <- c("a","b","c","d","e","f")
v[3] <- 1
v
[1] "a" "b" "1" "d" "e" "f"
You can also modify more than one element at once.
v <- c("a","b","c","d","e","f")
v[1:3] <- c(1,2,3)
v
[1] "1" "2" "3" "d" "e" "f"
Add Elements to a Vector
The c()
function can also be used to add elements to a vector.
v <- c(1,2,3)
# Add a single value to v
v <- c(v,4)
v
[1] 1 2 3 4
# Append an entire vector to v
w <- c(5,6,7,8)
v <- c(v,w)
v
[1] 1 2 3 4 5 6 7 8
Insert Element into a Vector
To insert an element into the middle of a vector, use append()
function.
# Insert 99 after 5th element
append(1:10, 99, after=5)
[1] 1 2 3 4 5 99 6 7 8 9 10
# Insert 99 at the start
append(1:10, 99, after=0)
[1] 99 1 2 3 4 5 6 7 8 9 10
Combine Multiple Vectors
If the arguments to the c()
function are vectors, it flattens them and combines them into one single vector.
# Combine three vectors
v1 <- c(1, 2, 3)
v2 <- c(4, 5, 6)
v3 <- c(7, 8, 9)
c(v1, v2, v3)
[1] 1 2 3 4 5 6 7 8 9
# Combine a vector and a sequence
v <- c(1, 2, 3)
c(v, 4:9)
[1] 1 2 3 4 5 6 7 8 9
Vector Arithmetic
Vector operations are one of R’s great strengths. All the basic arithmetic operators can be performed on pairs of vectors. Each operation is performed in an element-by-element manner.
v1 <- c(11,12,13,14,15)
v2 <- c(1,2,3,4,5)
# addition
v1 + v2
[1] 12 14 16 18 20
# subtraction
v1 - v2
[1] 10 10 10 10 10
# multiplication
v1 * v2
[1] 11 24 39 56 75
# division
v1 / v2
[1] 11.000000 6.000000 4.333333 3.500000 3.000000
# exponents
v1 ^ v2
[1] 11 144 2197 38416 759375
If one operand is a vector and the other is a scalar, then the operation is performed between every vector element and the scalar.
# Arithmetic operations on a vector and a scalar
v <- c(1,2,3,4,5)
# addition
v + 2
[1] 3 4 5 6 7
# subtraction
v - 2
[1] -1 0 1 2 3
# multiplication
v * 2
[1] 2 4 6 8 10
# division
v / 2
[1] 0.5 1.0 1.5 2.0 2.5
# exponents
v ^ 2
[1] 1 4 9 16 25
You can also apply a function on each element of a vector.
v <- c(1,2,3,4,5)
sqrt(v)
[1] 1.000000 1.414214 1.732051 2.000000 2.236068
log(v)
[1] 0.0000000 0.6931472 1.0986123 1.3862944 1.6094379
The Recycling Rule
Arithmetic operations are performed in an element-by-element manner. That works well when both vectors have the same length. But, when the vectors have unequal lengths, R’s Recycling Rule kicks in.
If we apply arithmetic operations to two vectors of unequal length, then the elements of the shorter vector are recycled to match the longest vector.
long <- c(1,2,3,4,5,6)
short <- c(1,2,3)
long + short
[1] 2 4 6 5 7 9
Here, the elements of long
and short
are added together starting from the first element of both vectors. When R reaches the end of the short
vector, it starts again at the first element of short
and continues until it reaches the last element of the long
vector.
Sort a Vector
You can sort a vector using the sort()
function. You can also specify the order in which you want to sort a vector.
# Sort an integer vector
v <- c(2,7,3,6,1,5,9)
sort(v,decreasing=FALSE)
[1] 1 2 3 5 6 7 9
sort(v,decreasing=TRUE)
[1] 9 7 6 5 3 2 1
# Sort a character vector
v <- c("f","c","g","a","d","e","b")
sort(v,decreasing=FALSE)
[1] "a" "b" "c" "d" "e" "f" "g"
sort(v,decreasing=TRUE)
[1] "g" "f" "e" "d" "c" "b" "a"
Find a Vector Length
To find the total number of elements in a vector, use length()
function.
v <- c(1,2,3,4,5)
length(v)
[1] 5
Calculate Basic Statistics
You can calculate basic statistics by using below simple R functions.
Statistic | Function |
mean | mean(x) |
median | median(x) |
standard deviation | sd(x) |
variance | var(x) |
correlation | cor(x, y) |
covariance | cov(x, y) |
These functions take a vector of numbers as an argument and return the calculated statistic.
v <- c(1,2,3,4,5,6)
# mean
mean(v)
[1] 3.5
# median
median(v)
[1] 3.5
# standard deviation
sd(v)
[1] 1.870829
# variance
var(v)
[1] 3.5
# correlation
cor(v, 2:7)
[1] 1
# covariance
cov(v, 2:7)
[1] 3.5